Where can i find the ThreadPool.SwitchTo method?

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方法?ThreadPool类中没有SwithcTo方法。
我有AsyncCtpLibrary.dll的引用...但是没有找到。

这对我来说看起来像是一个扩展方法。 - Tim Lloyd
所以我想,但从哪里开始?我已经添加了对AsyncCtpLibrary.dll的引用,但没有运气。 - Charles Okwuagwu
你必须添加正确的 using 才能使用扩展方法。 - Nekresh
1
@CharlesO:如果你已经解决了这个问题,请将其发布为答案,以帮助未来的其他人。 - Simon P Stevens
@chibacity,@Cody:等等,什么?静态类上的扩展方法何时变得可能了?! - Dan Tao
显示剩余4条评论
2个回答

2

供参考,CharlesO在上面的评论中回答了他的问题:

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

Public Shared Function SwitchTo() As System.Runtime.CompilerServices.YieldAwaitable,属于System.Threading.ThreadPoolEx成员。概述:创建一个可等待对象,当等待时异步地转换到线程池。


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!
  }

}

当然,您可以开发自定义的可等待和等待器类型来实现被删除的功能。但是,使用Task.Run1要比通过await在中途切换上下文更好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接