Strange behavior awaits

I have an asynchronous method like this

public async Task<bool> FooAsync() 
{ 
    return await SomeThirdPartyLib.SomeMethodReturningBoolAsync().ConfigureAwait(false);
}

      

Then I have some code that calls this in a loop:

for (var i = 0; i < 10; i++)
{
    ok &= await FooAsync().ConfigureAwait(false);
}

      

In my case, this will cause my process to hang after 2 or 3 or some other number of loops. But when I change the code to

for (var i = 0; i < 10; i++)
{
    ok &= await FooAsync()
        .ContinueWith(t => {
            if (t.IsCompleted)
            {
                return t.Result;
            }
            return false;
        })
        .ConfigureAwait(false);
}

      

the same code works. Any ideas?

Edit . I've modified my example code a bit to show what FooAsync

it does in principle. In response to some of the answers and comments already given: I don't know exactly what it does SomeMethodReturningBoolAsync

. The fact that mine ContinueWith

was actually nothing of use struck me.

+3


source to share


2 answers


Yours FooAsync()

, despite the name, actually does its job synchronously, so as you start working on the UI thread, it will continue to do all the work on the UI thread.

When you add to ContinueWith

, you force the method (which does nothing) to run on the thread pool thread, so that only the first call is FooAsync

actually made on the UI thread. All subsequent calls will be on the thread pool thread as a result ConfigureAwait(false)

.



The correct fix is ​​to actually set FooAsync

it up so that it actually does its job asynchronously and not synchronously, or if it doesn't conceptually do asynchronous work, then it should be a synchronous method, not return Task

and is called with Task.Run

in your method here since it has to do this synchronous work on a different thread.

+6


source


Answer inside your question what happened, explain that you are a Servy jet - just start a thread pool:



for (var i = 0; i < 10; i++)
{
 ok &= await Task.Run(() => { return FooAsync(); }).ConfigureAwait(false);
}

      

+1


source







All Articles