HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Thread overkill with async/await

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withasyncawaitoverkillthread

Problem

Consider the following code.

public async void Connect()
{
  bool success = await ConnectAsync();
  if (success) NotifyUserOfSuccess();
}

public async Task 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?

Solution

You have a wrong assumption here. await never starts a new thread! Strictly speaking even Task.Run might not start a new thread since it uses the thread pool.

See this answer for more details on await: https://stackoverflow.com/questions/16978904/async-programming-control-flow/16980183#16980183

Context

StackExchange Code Review Q#27989, answer score: 11

Revisions (0)

No revisions yet.