缺少 C# 后台线程属性



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

    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 个编译错误:

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

我不知道为什么

关于背景的事情,我不明白您希望如何设置它,因为您没有保留对线程的引用。应如下所示:

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);

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

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

最新更新