0

使用 ThreadPool 实现以下代码的等效方式是什么:

Receiver 是我正在实例化的一个类

foreach (MobileAccounts MobileAccount in ReceiverAccounts)
{                        
    Receiver rec = new Receiver();
    ThreadStart starterParameters = delegate { rec.StartListener(MobileAccount); };
    Thread FeedbackThread = new Thread(starterParameters);
    FeedbackThread.Name = MobileAccount.FriendlyName;

    FeedbackThread.Start();                                                                                           
}
4

3 回答 3

3

好吧,如果您切换到 ThreadPool,您不一定能够命名线程,但是您可以使用 Task Parallel 库来实现您的目标。TPL

一种方法是

foreach (MobileAccounts MobileAccount in ReceiverAccounts) {
  Receiver rec = new Receiver();
  Task.Run(() => rec.StartListener(MobileAccount));
}

甚至使用 Parallel.ForEach

Parallel.ForEach(ReceiverAccounts, 
                 MobileAccount => new Receiver().StartListener(MobileAccount));
于 2013-10-11T11:55:01.770 回答
0
  var tokenSource2 = new CancellationTokenSource();

  foreach (MobileAccounts MobileAccount in ReceiverAccounts)
  {
    var rec = new Receiver();
    var ct = tokenSource2.Token;
    Task.Factory.StartNew(() => this.DoWorkEventArgs(rec, ct));
  }

 // Anywhere outside you can call tokenSource2.Cancel();


 private void DoWorkEventArgs(Receiver rec, CancellationToken ct)
 {
   // Were we already canceled?
   ct.ThrowIfCancellationRequested();

   bool moreToDo = true;
   while (moreToDo)
   {
       // Poll on this property if you have to do 
       // other cleanup before throwing. 
       if (ct.IsCancellationRequested)
       {
         // Clean up here, then...
         ct.ThrowIfCancellationRequested();
       }
    }
 }
于 2013-10-11T13:32:34.997 回答
0

回答我原来的问题:

foreach (MobileAccounts MobileAccount in ReceiverAccounts)
{
    Receiver rec = new Receiver();

    ThreadPool.QueueUserWorkItem(delegate { rec.StartListener(MobileAccount); }, null);                    


}
于 2013-10-17T14:32:42.907 回答