等待后在UI线程中运行的异步长阻塞方法 [英] async long blocking method running in the UI thread after awaiting

查看:66
本文介绍了等待后在UI线程中运行的异步长阻塞方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

周围的东西:

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

但是问题是,它在等待之后仍然在UI线程中运行.我通过获取UI线程和等待后的线程的Thread.CurrentThread.ManagedThreadId来确保,并且UI线程变得没有响应.

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.

那我该怎么办?我应该以传统方式使用线程,而不是依靠异步/等待吗?还是有办法让它在等待之后在新的非UI线程中运行?

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 ?

推荐答案

但是问题在于,它在等待之后仍然在UI线程中运行.

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

是的,会的.这是 async / await 的全部内容的一半-您可以返回到正确的上下文.

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

听起来好像您真的应该启动一个新线程(或者最好使用 Task< T> )进行后台操作(如果无法避免)阻止IO.然后,您可以在异步方法中使用结果:

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
}

这篇关于等待后在UI线程中运行的异步长阻塞方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆