NotSupportedException on WaitHandle.WaitAll

后端 未结 3 1800
名媛妹妹
名媛妹妹 2021-01-19 07:17

I am trying to execute the following code. The code tries to parallely download and save images. I pass a list of images to be downloaded. I wrote this in C# 3.0 and compile

相关标签:
3条回答
  • 2021-01-19 07:41

    Did you mark one of the methods with [STAThread] attribute?

    0 讨论(0)
  • 2021-01-19 07:54

    I advise against using multiple WaitHandle instances to wait for completion. Use the CountdownEvent class instead. It results in more elegant and scalable code. Plus, the WaitHandle.WaitAll method only supports up to 64 handles and cannot be called on an STA thread. By refactoring your code to use the canonical pattern I came up with this.

    public static void SpawnThreads(List<string> imageList)
    { 
      imageList = new List<string>(imageList); 
      var finished = new CountdownEvent(1);
      var picDownloaders = new PicDownloader[imageList.Count]; 
      ThreadPool.SetMaxThreads(MaxThreadCount, MaxThreadCount); 
      for (int i = 0; i < imageList.Count; i++) 
      { 
        finished.AddCount();    
        PicDownloader p = new PicDownloader(imageList[i]); 
        picDownloaders[i] = p; 
        ThreadPool.QueueUserWorkItem(
          (state) =>
          {
            try
            {
              p.DoAction
            }
            finally
            {
              finished.Signal();
            }
          });
      } 
      finished.Signal();
      finished.Wait();
      Console.WriteLine("All pics downloaded"); 
    } 
    
    0 讨论(0)
  • 2021-01-19 07:59

    Have you tried setting the apartment state for the thread?

    thread.SetApartmentState (System.Threading.Apartmentstate.MTA );
    
    0 讨论(0)
提交回复
热议问题