Click here to Skip to main content
15,907,492 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
VB.NET
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


The CallBack_Import procedure is fulfilled after ImportTransfers procedure end, but how to stop ImportTransfers by button btn_StopProcess Click?
Posted
Updated 26-Apr-10 0:10am
v2

1 solution

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;



And then in your btn_StopProcess_Click()
this.asynchOperation.Abort();


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
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900