Obviously, there is tons of stuff online about .NET's growing number of ways to multithread code. And that's the problem - working out not just which one to use but how to avoid unnecessarily (and possibly dangerously) mixing approaches.
My requirements seem straightforward enough:
1. I want to start a background task (a Bluetooth reconnection) from an event handler.
2. I want the event handler to end quickly.
3. I want to be able to run some code when the background work completes.
4. I want to catch any exceptions.
5. I want to avoid nightmares caused by the numerous warnings to avoid
async void
.
I'd be grateful for advice about to satisfy these requirements with readable and safe code.
What I have tried:
What I suspect is a mix-n-match hotchpotch of the available options.
Also in an attempt to use the
BackgroundWorker
suggested by @OriginalGriff, I now have something that looks like this:
void BLEAdapter_DeviceConnectionLost( object sender, DeviceErrorEventArgs e )
{
_reconnectBLEWorker = new BackgroundWorker();
_reconnectBLEWorker.DoWork += ReconnectBLEWorker_DoWork;
_reconnectBLEWorker.RunWorkerCompleted += ReconnectBLEWorker_RunWorkerCompleted;
_reconnectBLEWorker.RunWorkerAsync();
}
async void ReconnectBLEWorker_DoWork( object sender, DoWorkEventArgs e )
{
int retryCount = 0;
while( !_bluetoothConnected && retryCount < 10 )
{
await KnownDeviceReconnection();
++retryCount;
}
}
async Task KnownDeviceReconnection()
{
try
{
IDevice device = await App.BLE.Adapter.ConnectToKnownDeviceAsync( _lastConnectedDeviceGuid );
}
catch( Exception ex )
{
}
}
void ReconnectBLEWorker_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e )
{
}
This is not working. Clearly I am misunderstanding how
async/await
works because I just don't get why, in the code above, the
BackgroundWorker
work thread ends immediately.