C#后台线程属性丢失

时间:2012-10-04 10:20:50

标签: c# multithreading

我想将我的Thread配置为后台线程,为什么我的线程中缺少此属性?

    ThreadStart starter = delegate { openAdapterForStatistics(_device); };
    new Thread(starter).Start();

public void openAdapterForStatistics(PacketDevice selectedOutputDevice)
{
    using (PacketCommunicator statCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the output adapter
    {
        statCommunicator.Mode = PacketCommunicatorMode.Statistics; //put the interface in statstics mode                
        statCommunicator.ReceiveStatistics(0, statisticsHandler);

    }
}

我试过了:

Thread thread = new Thread(openAdapterForStatistics(_device));

但我有2个编译错误:

  
      
  1. 'System.Threading.Thread.Thread(System.Threading.ThreadStart)'的最佳重载方法匹配有一些无效的参数
  2.   
  3. 参数1:无法从'void'转换为'System.Threading.ThreadStart'
  4.   

我不知道为什么

3 个答案:

答案 0 :(得分:1)

关于后台的事情,我没有看到你期望如何设置它,因为你没有保持对线程的引用。应该是这样的:

ThreadStart starter = delegate { openAdapterForStatistics(_device); };
Thread t = new Thread(starter);
t.IsBackground = true;
t.Start();

Thread thread = new Thread(openAdapterForStatistics(_device));

将无效,因为您应该传递一个以object作为参数的方法,而实际上是在传递方法调用的结果。所以你可以这样做:

public void openAdapterForStatistics(object param)
{
    PacketDevice selectedOutputDevice = (PacketDevice)param;
    using (PacketCommunicator statCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the output adapter
    {
        statCommunicator.Mode = PacketCommunicatorMode.Statistics; //put the interface in statstics mode                
        statCommunicator.ReceiveStatistics(0, statisticsHandler);

    }
}

Thread t = new Thread(openAdapterForStatistics);
t.IsBackground = true;
t.Start(_device);

答案 1 :(得分:0)

您应该使用BackgroundWorker类,它专门用于您的情况。您希望在后台完成的任务。

答案 2 :(得分:0)

PacketDevice selectedOutputDeviceValue = [some value here];
Thread wt = new Thread(new ParameterizedThreadStart(this.openAdapterForStatistics));
wt.Start(selectedOutputDeviceValue);