0

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

    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. 参数 1:无法从 'void' 转换为 'System.Threading.ThreadStart'

我不知道为什么

4

3 回答 3

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);
于 2012-10-04T10:22:50.690 回答
0

您应该使用BackgroundWorker该类,该类是专门为像您的情况一样使用而设计的。您希望在后台完成的任务。

于 2012-10-04T10:22:53.573 回答
0
PacketDevice selectedOutputDeviceValue = [some value here];
Thread wt = new Thread(new ParameterizedThreadStart(this.openAdapterForStatistics));
wt.Start(selectedOutputDeviceValue);
于 2012-10-04T10:32:59.183 回答