跨线程调用WF控件

时间:2010-09-18 12:25:56

标签: c# winforms multithreading

我正在使用SharpPcap库。我有以下代码:

private void button1_Click(object sender, EventArgs e)
    {
        LivePcapDevice device = deviceList[cbDeviceList.SelectedIndex];
        device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);
        device.Open(DeviceMode.Promiscuous, 1000);
        device.StartCapture();
        btStop.Enabled = true;
        btStartCapture.Enabled = false;
    }

void device_OnPacketArrival(object sender, CaptureEventArgs e)
    {         
        dgvPacketInfo.Rows.Add(e.Packet.Data, e.Packet.Timeval,
                                e.Packet.LinkLayerType);          
    }

我抛出异常:InvalidOperationException,消息“控制dgvPacketInfo从其创建的线程以外的线程访问。”我看了this。 并重写我的代码:

private delegate void GetPacketInfoCallback(CaptureEventArgs packet);

void device_OnPacketArrival(object sender, CaptureEventArgs e)
    {
        Thread newThread = new Thread(delegate()
                                          {
                                              GetPacketInfoCallback getPacketInfoCallback = new GetPacketInfoCallback(PrintIntoGridView);
                                              this.Invoke(getPacketInfoCallback, new object[] {e});
                                          });            
    }

private void PrintIntoGridView(CaptureEventArgs captureEventArgs)
    {
        dgvPacketInfo.Rows.Add("1", "2", "3"); // simple for test
        dgvPacketInfo.Rows.Add(captureEventArgs.Packet.Data, captureEventArgs.Packet.Timeval,
                               captureEventArgs.Packet.LinkLayerType);
    }

但是没有调用方法PrintIntoGridView。什么问题? PS。抱歉我的英文。

1 个答案:

答案 0 :(得分:1)

我猜device_OnPacketArrival已经在与GUI线程不同的线程上执行,因此产生另一个线程就没有必要了。试试这个:

void device_OnPacketArrival(object sender, CaptureEventArgs e)
{
    if (InvokeRequired)
    {
        // If this is executing on a different thread than the GUI thread
        var getPacketInfoCallback = new GetPacketInfoCallback(PrintIntoGridView);
        Invoke(getPacketInfoCallback, new object[] { e });
    } 
    else 
    {
        // This is the GUI thread => 
        // you can safely modify GUI controls
        PrintIntoGridView(e);
    }
}

private void PrintIntoGridView(CaptureEventArgs captureEventArgs)
{
    dgvPacketInfo.Rows.Add("1", "2", "3"); // simple for test
    dgvPacketInfo.Rows.Add(
        captureEventArgs.Packet.Data, 
        captureEventArgs.Packet.Timeval,
        captureEventArgs.Packet.LinkLayerType
    );
}