用C#监听同步回调

时间:2013-09-24 07:30:48

标签: c# callback synchronous

我有一个程序将数据写入USB HID设备。当从USB设备接收数据时,我通过委托事件usblibDataRecievedEventHandler库获得回调。

我习惯使用中断编程固件,以便我可以

while(!flag); // Will continue when interrupt triggers and change the flag

我想逐个元素地向USB写一个数组元素并等待每个数组元素后从设备返回

for (int i = 0; i > 16; i++)
{ 
    sendUsbData(array[i]);
    while(!receivedComplete);
    // Wait for response from USB before transmitting next iteration
}

问题是当我在while循环中假脱机时,回调不会被触发。关于如何进行这类操作的任何建议?

我用于USB通信的库与this one相同。在 SpecifiedDevice.cs 中,有一个名为public void SendData(byte[] data)的方法,我用它来发送字节数组。

传播方法:

public void sendUsbData(byte _txData)
{
    byte[] txData = new byte[this.usb.SpecifiedDevice.OutputReportLength];
    txData[1] = 0x50; // 0x50 = loopback command. Element 0 is always 0x00

    int pos = 2;
    foreach (byte b in _flashData)
    {
        txData[pos] = b;
        pos++;
    }

        this.usb.SpecifiedDevice.SendData(txData);
}

从USB接收数据后,将调用回调usb_OnDataRecieved

private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
{
    this.ParseReceivePacket(args.data); // Format to string and print to textbox
    /*public bool*/receiveComplete = true; 
}

1 个答案:

答案 0 :(得分:1)

您可以切换到使用AutoResetEvent等待句柄:

public void sendUsbData(byte _txData)
{
  byte[] txData = new byte[this.usb.SpecifiedDevice.OutputReportLength];
  txData[1] = 0x50; // 0x50 = loopback command. Element 0 is always 0x00

  int pos = 2;
  foreach (byte b in _flashData)
  {
    txData[pos] = b;
    pos++;
  }

  // reset member wait handle
  waitHandle = new AutoResetEvent(false); 
  this.usb.SpecifiedDevice.SendData(txData);
}

private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
{
  this.ParseReceivePacket(args.data); // Format to string and print to textbox

  // signal member wait handle
  waitHandle.Set();
}

然后在你的for循环中:

for (int i = 0; i > 16; i++)
{ 
  sendUsbData(array[i]);

  // wait for member wait handle to be set
  waitHandle.WaitOne();
}