假设我正在调用一些我无法控制的网络服务方法。这种方法运行时间很长,开发web服务的人没想到要包含异步版本。
在 C#/winforms 中为此类方法创建异步包装器的最佳方法是什么?
目前我正在使用 ThreadPool 来运行 web 服务方法,然后在 web 服务完成时调用一个事件。像这样。
DoWorkAsync() {
Webservice.LongMethod()
WorkCompleteEvent()
}
但是,这似乎并不理想。例如,如果我尝试从事件处理程序修改表单控件,我会收到一条警告,告诉我不要从不同的线程等进行修改。
有没有人对解决这个问题有任何其他建议?
请您参考如下方法:
请参阅有关 How to: Make Thread-Safe Calls to Windows Forms Controls 的 MSDN 文章还有 Jon Skeet 的精彩 guide to threading更具体地说 Threading in Windows Forms .
引用 Jon(强调我的):
Never invoke any method or property on a control created on another thread other than Invoke, BeginInvoke, EndInvoke or CreateGraphics, and InvokeRequired. Each control is effectively bound to a thread which runs its message pump. If you try to access or change anything in the UI (for example changing the Text property) from a different thread, you run a risk of your program hanging or misbehaving in other ways. You may get away with it in some cases, but only by blind luck. Fortunately, the Invoke, BeginInvoke and EndInvoke methods have been provided so that you can ask the UI thread to call a method for you in a safe manner.
