中止异步操作 [英] Abort the asynchronous operation
问题描述
有人可以告诉我如何终止异步操作吗?
这样的问题.
我创建了从不同数据库收集一些信息的应用程序.而且此过程可能非常持久,因此我将收集过程称为异步过程,它有可能随时中断.
我所做的:
Hi,
Can anybody tell me how to abort the asynchronous operation?
Problem such.
I have created the application which gathers some information from different databases. And this process can be very durable, therefore I call procedure of collection asynchronous that there was a possibility it to interrupt at any time.
That I have made:
Public class Manager
Public Sub ImportTransfers
'Collect information
End Sub
End class
Public Class frm_Main
Delegate Sub dlg_Importer()
Dim Importer As dlg_Importer
Dim CallBackImport As AsyncCallback
Private Sub frm_Main_Load
Call Init_Delegates()
End Sub
Private Sub Init_Delegates()
Importer = AddressOf Manager.ImportTransfers
CallBackImport = AddressOf CallBack_Import
End Sub
Private Sub btn_ImportTransfers_Click
Importer.BeginInvoke(CallBackImport, Nothing)
End Sub
Sub CallBack_Import(ByVal ar As IAsyncResult)
Importer.EndInvoke(ar)
End Sub
Private Sub btn_StopProcess_Click
'I do not know what to write here to stop process...
End Sub
End Class
CallBack_Import过程在ImportTransfers过程结束后完成,但是如何通过按钮btn_StopProcess单击来停止ImportTransfers?
The CallBack_Import procedure is fulfilled after ImportTransfers procedure end, but how to stop ImportTransfers by button btn_StopProcess Click?
推荐答案
Makso,我认为异步调用不会解决你的问题.您唯一的解决方案是将该异步线程的引用发送回主线程,这是非常肮脏的解决方案.
我的意思是设置表单级别变量
Makso, I don''t think that asynchronous call will solve your problem. The only solution you have is to send a reference of that asynchronous thread back to the main thread, a very very dirty solution.
What I mean is setting up a form level variable
System.Threading.Thread asynchOperation;
然后在您的异步方法中像这样设置它.
And in your asynchronous method just set it like this.
this.asynchOperation = System.Threading.Thread.CurrentThread;
然后在您的btn_StopProcess_Click()
And then in your btn_StopProcess_Click()
this.asynchOperation.Abort();
另外,不要忘记将异步操作包装在try catch和catching System.Threading.ThreadAbortException.
中
但我会严格建议不要使用此解决方案.中止 ThreadPool 线程不是一个主意,任何人都会喜欢.据报道,它还是可以重新创建的.作为一个实验,我本人放弃了大约70个线程,每次我返回带有ManagedID 6的线程.我尚未确认非托管状态,但至少它正在重新创建这些线程.
更好的解决方案是显式使用 Thread 类
Also don''t forget to wrap your asynchronous operation in try catch and catching System.Threading.ThreadAbortException.
But i will strictly advise against this solution. Aborting a ThreadPool thread is not an idea, anyone will favor. It''s reported to be recreated anyway. I myself has aborted as an experiment about 70 threads and everytime i got back a thread with managedID 6. I haven''t confirmed the unmanaged status, but at least it was recreating these threads.
A better solution would be using Thread class Explicitly
这篇关于中止异步操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!