0

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 ?

4

1 に答える 1

4

しかし、問題は、待機後も UI スレッドで実行されることです。

はい、そうです。asyncこれが/の要点の半分です。つまりawait、正しいコンテキストに戻ることができるということです。

ブロッキング IO を回避できない場合は、バックグラウンド操作のために新しいスレッドを開始する (または、できれば を使用する)必要があるようです。次に、非同期メソッドで結果を使用Task<T>できます。

async Task Foo(...)
{
    string result = await Task.Run(...);
    // Now update the UI with the result
}
于 2012-10-25T14:40:37.447 に答える