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 に答える