我是线程新手,在这个问题上停留在这里。我有一个使用多线程的应用程序。我有一个在 ftp 服务器上上传数千张图像的功能。对于每个图像,我正在创建一个新线程。该线程调用一个函数来连接ftp服务器,上传文件,如果上传成功返回布尔值。
我的问题是,由于我上传了数千张图像并且每个图像都在创建自己的线程,因此在一段时间后我得到内存不足异常并且应用程序冻结。
我的代码如下:
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;
}
请帮助并让我知道如何限制创建的线程数,以便一次运行的线程不超过 10-20 个。