0

更新

我现在想知道 foreach 循环在这里迭代的 IEnumerable 是否来自使用 yield return 的循环。我不确定这是否对线程有任何影响......?


谁能指出为什么我从未在此代码中看到 BackgroundWorker RunWorkerCompleted 事件触发(这是一个 .NET 4、MVC 3 应用程序)?

无论我设置什么,WorkerSupportsCancellationWorkerReportsProgress完成的事件似乎永远不会触发。

即使我尝试在 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 { }
4

1 回答 1

-1

这段代码中有很多奇怪的怪癖——执行代码的线程是在你的主线程还是其他线程之上?无论哪种方式,如果它是您的 GUI 线程,那么它会阻塞 (.Sleep(3000)),如果不是,那么您会在错误的上下文中创建您的后台工作线程

于 2012-10-12T13:15:32.710 回答