2012-10-12 4 views
0

업데이트C# 배경 작업자 RunWorkerCompleted 절대 화재 - 왜?

는 지금 궁금하네요 경우, 사실 여기를 통해 foreach 루프 반복 수율 반환을 사용하는 루프에서라는 IEnumerable을 그. 이 스레딩에 어떤 영향이 있는지 확실하지 않습니다 ...?


나는 결코이 코드에서 BackgroundWorker에 RunWorkerCompleted 이벤트 화재 (이, MVC 3 응용 프로그램 닷넷 4) 볼 사람이 왜 지적 할 수 있습니까?

에 관계없이 내가 설정 무엇을, WorkerSupportsCancellationWorkerReportsProgress이 완료된 이벤트가 발생하는 것 없다.

DoWork 블록에서 예외를 throw하려고해도 완성 된 이벤트가 표시되지 않습니다. 내가 이해할 때, 나는해야만한다.

여기에서 확실한 것은 무엇입니까?

그런데 프로젝트 제한으로 인해 새로운 비동기 기능을 사용하려면 프로젝트를 .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 { } 
+1

'작업 '을 사용하고 있습니까? 이 경우에는 지원이 훨씬 쉬울 것이며 .NET 4.0에서 사용할 수 있습니다. – casperOne

+0

파일 스트림이 차단되어있을 수 있습니다. 파일에 액세스 할 수 있습니까? – Silvermind

+0

@ Silvermind 예, 파일의 모든 핸들이 닫혔습니다. – gb2d

답변

-1

은 - 주 스레드 또는 다른 스레드 위의 코드를 실행하는 스레드? 어느 쪽이든, GUI 스레드라면 차단하고 (.Sleep (3000)), 틀린 상황에서 배경 작업자를 만듭니다.

+0

수면은 백그라운드 스레드의 생성을 제어하는 ​​것이며 배경 작업자가 실행하는 스레드를 차단하지 않습니다. – gb2d

+0

"많은 이상한 버크 (dir)"... 생각하는 것을 나열하면 도움이됩니다. –

+0

코드가 실행되는 스레드를 알면 대답하기가 쉽지만 현재 알려지지 않았습니다. 그리고 코드의 목적이 무엇인지 이해하지 못합니다. 코드의 컨텍스트와 목적을 알고 있으면 단점 목록을 채우기가 더 쉽습니다. – Onkelborg