简体   繁体   中英

async long blocking method running in the UI thread after awaiting

Its something around:

async Task foo(...)
{
   await Task.Yield();
   [long blocking I/O statements]
}

But the problem is that it still runs in the UI thread after the await. I made sure by getting the Thread.CurrentThread.ManagedThreadId for both the UI thread and the thread after await, and the UI thread is becoming not responsive.

So what should I do ? Should I use threads in the traditional way instead of relying on async/await ? or is there a way to make it run in a new non-UI thread after the await ?

But the problem is that it still runs in the UI thread after the await.

Yes, it would. That's half the whole point of async / await - that you get to come back to the right context.

It sounds like you really should start a new thread (or preferably, use a Task<T> ) for the background operation, if you can't avoid the blocking IO. Then you can use the result in an async method:

async Task Foo(...)
{
    string result = await Task.Run(...);
    // Now update the UI with the result
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM