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
Use the
This has other benefits, like
progress monitoring, and
"Work complete" callbacks. It also nicely
handles exceptions.
Use
Create your own
详见:http://stackoverflow.com/questions/1729346/how-to-cancel-an-asynchronous-call
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
BackgroundWorkerinstead 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
Cancelledflag 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
BackgroundWorkerdoes for you - you have a component on your form. (Thanks toFredrik for reminding about this).
Create your own
ThreadStartdelegate, passing in a state object as with option 2.
详见:http://stackoverflow.com/questions/1729346/how-to-cancel-an-asynchronous-call
相关文章推荐
- 《在C#中实现Socket端口复用》 以及《 UDP 一个封锁操作被对 WSACancelBlockingCall 的调用中断。》问题
- 《在C#中实现Socket端口复用》 以及《 UDP 一个封锁操作被对 WSACancelBlockingCall 的调用中断。》
- 《在C#中实现Socket端口复用》 以及《 UDP 一个封锁操作被对 WSACancelBlockingCall 的调用中断。》问题
- In C how do you redirect stdin/stdout/stderr to files when making an execvp() or similar call?
- 一个封锁操作被对 WSACancelBlockingCall 的调用中断
- All-In-One Code Framework(AIO): 如何使用C#编写进程外的COM组件 (How to write an out-of-proc COM server in C#)
- 一个封锁操作被对WSACancelBlockingCall的调用中断
- UDP 一个封锁操作被对 WSACancelBlockingCall 的调用中断
- How to call an Objective-C Method from a C Method?
- WCF分布式开发常见错误(13):The transaction under which this method call was executing ,此方法调用的事务被异步中断
- 一个封锁操作被对 WSACancelBlockingCall 的调用中断
- <转>[C#][Tutorial] How to become an EndScene() hooker
- How to call an Oracle Stored Procedure that returns one or more REF CURSORS, using ADO from C++ How
- How to cancel an invoice
- how to call the procedure in c# program
- APC -- Asynchronous Procedure Call 异步过程调用
- [Socket网络编程]一个封锁操作被对 WSACancelBlockingCall 的调用中断。
- DeprecationWarning: Calling an asynchronous function without callback is deprecated. - how to find where the “function:” is?
- 一个封锁操作被对 WSACancelBlockingCall 的调用中断 ErrorCode=10004
- 如何把string解析为int?[C#] How to Parse a string to an int? [C#]