3

我正在研究新的 Async CTP 并通过一些示例代码,

我遇到了这段代码:

public async void button1_Click(object sender, EventArgs e) 
{ 
string text = txtInput.Text; 

await ThreadPool.SwitchTo(); // jump to the ThreadPool 

string result = ComputeOutput(text); 
string finalResult = ProcessOutput(result); 

await txtOutput.Dispatcher.SwitchTo(); // jump to the TextBox’s thread 

txtOutput.Text = finalResult; 
}

请问在哪里可以找到 ThreadPool.SwitchTo?SwithcTo 方法不在 ThreadPool 类上

我有一个 AsyncCtpLibrary.dll 的参考...但没有运气

4

2 回答 2

2

作为参考,CharlesO 在上述评论中回答了他的问题:

好的,找到了,总结:提供与线程池交互的方法。备注:ThreadPoolEx 是一个占位符。

公共共享函数 SwitchTo() As System.Runtime.CompilerServices.YieldAwaitable System.Threading.ThreadPoolEx 的成员 摘要:创建一个在等待时异步让给 ThreadPool 的 awaitable。

于 2011-03-18T02:45:42.610 回答
1

ThreadPool.SwitchTo大概是因为它是一种反模式而被删除。考虑一下如果在切换回原始上下文之前抛出异常会发生什么。您不能使用finally块作为对抗措施来防范该异常并切换回来,因为await不能出现在finally块中。

public async void button1_Click(object sender, EventArgs e) 
{ 
  await ThreadPool.SwitchTo();
  try
  {
    // Do something dangerous here.
  }
  finally
  {
    await button1.Dispatcher.SwitchTo(); // COMPILE ERROR!
  }

}

当然,您可以开发自定义的 awaitable 和 awaiter 类型来准确实现删除的内容。但是,使用Task.Run1比通过await.

于 2011-12-14T17:51:37.483 回答