c#' Calling Invoke() with async delegate

Viewed 239

I have a WinForms (.NET 4.7.2) app reading data from serial barcode scanner and returning it back to GUI.

My async SerialDataReceivedEventHandler is:

private async void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   if (_serialPort != null && _serialPort.IsOpen)
   {
       string data = _serialPort.ReadExisting();
       if (this.InvokeRequired)
       {
          this.Invoke(new Func<Task>(async () => await HandleDataFromScannerAsync(data)));
       }             
   }
}

private async Task HandleDataFromScannerAsync(string text) {
...do async stuff...
}

I have to use Invoke() in Port_DataReceived(), because the data from serial scanner are read in different thread.

This code is working, but...is it properly asynchronnous? I'm aware of calling async void methods.

I read Stephen Cleary's article about Synchronous and Asynchronous Delegate Types, and that's why I'm using new Func<Task>(async () => await HandleDataFromScannerAsync(data)).

So when calling Invoke(), shouldn't it be awaited in some way? Like await this.Invoke(...) or somehow. I tried BeginInvoke() instead of Invoke(). I understand the difference, but I'm not sure which is the right way. Both ways seem to work.

So my question is - how to properly call Invoke() with asynchronous delegate?

0 Answers
Related