public Byte[] WriteRead(Byte[] bytesToSend){ this.FrameReceived += Device_FrameReceived; this.Write(bytesToSend); // Send bytes to the device Boolean signaled = this.autoResetEvent.WaitOne(); // Wait for response (FrameReceived event) this.FrameReceived -= Device_FrameReceived; if (signaled) { return this.incomingBytes; } else { return null; }}After receiving the bytes, AutoResetEvent.Set is called, to unblock the WriteRead-Method.
private void Device_FrameReceived(Object sender, FrameReceivedEventAgs e){ this.incomingBytes = e.Frame; this.autoResetEvent.Set();}The code above works if it's executed before Thread.Sleep is called in the Main-Method. If the code is executed after Thread.Sleep, the code doesn't work. Device_FrameReceived is never called.
public static void Main(){ device = new Device(); device.FrameReceived += device_FrameReceived; // This will work, because Thread.Sleep isn't called // Byte[] bytes = device.WriteRead(bytesToSend); Thread.Sleep(Timeout.Infinite);}private static void device_FrameReceived(Object sender, FrameReceivedEventAgs e){ // This won't work, beacause Thread.Sleep is already called Byte[] bytes = device.WriteRead(bytesToSend);}I attached a sample application which demonstrates the problem, maybe someone is willing to explain me the problem and how to solve it.
Attached Files
- Claiskessed and entipttug like this