I am new to threading and stuck here on this issue. I have an application where I am using multi threading. I have a function which uploads thousands of images on ftp server. For each images I am creating a new thread. This thread calls a function to connect ftp server, upload file and returns boolean value if its successfully uploaded.
My problem is, since I am uploading thousands of images and each is creating its own thread, after sometime I get Out of Memory exception and application freezes.
My codes is as follows:
public Int16 UploadFiles(string[] files)
{
foreach (var fileName in files)
{
if (UploadFile(fileName))
{
strLogText += "\r\n\tFile: " + fileName + " downloaded.";
}
}
}
private bool UploadFile(string fileName)
{
var blnDownload = false;
var thread = new Thread(() => DownLoadFileNow(fileName, out blnDownload)) {IsBackground = true};
thread.Start();
return blnDownload;
}
private void DownLoadFileNow(string fileName, out bool blnDownload)
{
//Get file path and name on source ftp server
var srcFolder = GetSrcFolderName(fileName);
//Get Local Folder Name for downloaded files
var trgFolder = GetLocalFolder(fileName, "D");
var reqFtp =
(FtpWebRequest) WebRequest.Create(new Uri("ftp://" + _strSourceFtpurl + srcFolder + "/" + fileName));
reqFtp.Method = WebRequestMethods.Ftp.DownloadFile;
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(_strSourceFtpUser, _strSourceFtpPassword);
var outputStream = new FileStream(trgFolder + "\\" + fileName, FileMode.Create);
try
{
var response = (FtpWebResponse) reqFtp.GetResponse();
var ftpStream = response.GetResponseStream();
const int bufferSize = 2048;
var buffer = new byte[bufferSize];
if (ftpStream != null)
{
int readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
}
response.Close();
blnDownload = true;
}
catch (WebException ex)
{
_log.WriteLog("Error in Downloading File (" + fileName + "):\r\n\t" + ex.Message, "");
//Delete newly created file from local system
outputStream.Close();
if (File.Exists(trgFolder + "/" + fileName))
File.Delete(trgFolder + "/" + fileName);
}
catch (Exception ex)
{
_log.WriteLog("Error in Downloading File (" + fileName + "):\r\n\t" + ex.Message, "");
}
finally
{
outputStream.Close();
outputStream.Dispose();
}
blnDownload = false;
}
Please help and let me know how I can limit the number of threads being created so that at a time, there are not more than 10-20 threads running.