更新
我现在想知道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 { }
答案 0 :(得分:-1)
这段代码中有许多奇怪的怪癖 - 执行主线程或其他线程上方代码的线程是什么?无论哪种方式,如果它是你的GUI线程然后它阻塞(.Sleep(3000)),如果不是,那么你在错误的上下文中创建你的背景工作者