Consider the following code.
public async void Connect()
{
bool success = await ConnectAsync();
if (success) NotifyUserOfSuccess();
}
public async Task<bool> ConnectAsync()
{
var t = await Task.Run(()=>
try {
ConnectSynchronously();
} catch (Exception e)
{
return false;
}
return true;
);
}
When analyzing this code, I come to the conclusion that I potentially am kicking off three threads.
Assume that both await's will not already be completed when called, then the first thread is kicked off by the await ConnectAsync(); which in turn kicks off the await Task, and the Task.Run will kick off the function inside in a third thread.
I really only need one thread, namely the one in Connect().
How can I improve the design?
As Connect() contains the await keyword, shouldn't it really be called ConnectAsync() regardless of its return value?