更新
我现在想知道 foreach 循环在这里迭代的 IEnumerable 是否来自使用 yield return 的循环。我不确定这是否对线程有任何影响......?
谁能指出为什么我从未在此代码中看到 BackgroundWorker RunWorkerCompleted 事件触发(这是一个 .NET 4、MVC 3 应用程序)?
无论我设置什么,WorkerSupportsCancellation和WorkerReportsProgress完成的事件似乎永远不会触发。
即使我尝试在 DoWork 块中抛出异常,我也从未看到完成的事件。据我了解,我应该。
这里有什么明显的吗?
顺便说一句,由于项目限制,我无法将项目升级到 .NET 4.5 以使用更新的异步功能。
var autoResetEvent = new AutoResetEvent(false);
UploadsExpected = pagesFound;
foreach (var rasterisedPageFilePath in rasterisedPageFilePathList)
{
// Track uploads
UploadsStarted += 1;
int uploadCount = UploadsStarted;
// Track concurrent uploads in main thread and while we are at our
// maximum, pause and wait before starting the next upload thread
while (ConcurrentUploadsRunning >= maxConcurrentUploads)
{
Debug.WriteLine(string.Format("Waiting to start upload: {0}",
uploadCount));
Thread.Sleep(3000);
}
ConcurrentUploadsRunning += 1;
Debug.WriteLine(string.Format("Initiating new upload: {0}", uploadCount));
// Create a background worker so we can run the upload asynchronously.
var backgroundWorker = new BackgroundWorker();
// Set up anonymous method that runs asynchronously
backgroundWorker.DoWork += (sender, e) =>
{
try
{
var storageManager = new storageManager(awsS3BucketName);
string imgFilePath = (string) e.Argument;
using (var fileStream = new FileStream(imgFilePath, FileMode.Open))
{
storageManager.Save(Path.GetFileName(imgFilePath),
MimeTypes.JPEG, fileStream);
}
}
catch (Exception ex)
{
UploadHasFailed = true;
m_logManager.Fatal("Upload of file to AWS S3 has failed", ex);
}
// Run check for AutoResetEvent following Save complete,
// and if the completed uploads count indicates that all uploads
// have finished, set AutoResetEvent so main thread can exit
if ((UploadsCompleted += 1) == UploadsExpected)
{
autoResetEvent.Set();
}
Debug.WriteLine(string.Format("Upload complete: {0}", uploadCount));
ConcurrentUploadsRunning -= 1;
};
backgroundWorker.RunWorkerCompleted += (sender, args) =>
{
// Never fires
};
backgroundWorker.ProgressChanged += (sender, args) =>
{
// Never fires
};
backgroundWorker.RunWorkerAsync(rasterisedPageFilePath);
}
autoResetEvent.WaitOne();
try
{
inputStream.Close();
} catch { }