您的位置:首页 > 编程语言 > C#

How to cancel an asynchronous call? 异步调用 的中断 取消 c#

2013-12-09 20:30 501 查看
A "cancel flag" is the way to do it, though not a global one, necessarily. The unavoidable point is that you needsome way to signal to the thread that it should stop what it's doing.

In the case of
BeginInvoke
, this is hard to do with anything but a global flag, because the work is carried out on the threadpool, and you don't know which thread. You have a couple of options (in order of preference):

Use the
BackgroundWorker
instead of
BeginInvoke
. This hascancellation functionality baked-in.
This has other benefits, like
progress monitoring, and
"Work complete" callbacks. It also nicely
handles exceptions.
Use
ThreadPool.QueueUserWorkItem
, passing in an object as the state that has a
Cancel()
method that sets a
Cancelled
flag that the executing code can check. Of course you'll need to keep a reference to the state object so you can call
Cancel()
on it (which is something the
BackgroundWorker
does for you - you have a component on your form. (Thanks toFredrik for reminding about this).
Create your own
ThreadStart
delegate, passing in a state object as with option 2.

详见:http://stackoverflow.com/questions/1729346/how-to-cancel-an-asynchronous-call
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐