Asynchronous method call in .net framework 3.5 c#

Asynchronous method call in .net framework 3.5 c#

Added by Mind Hunter updated on Wednesday, February 7, 2018

Asynchronous Programming .Net 3.5:

We have lot of options for asynchronous programming in .Net framework 4.0 and 4.5 and above. But sometimes we need to call methods asynchronously in .Net 3.5, We have options to use third party nugget packages.

Asynchronous Programming Using Delegates

If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller. The target method is called asynchronously on a thread from the thread pool. The original thread, which submitted the request, is free to continue executing in parallel with the target method.

The BeginInvoke has the same parameters as the method that you want to execute asynchronously, plus two additional optional parameters. The first parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes. The second parameter is a user-defined object that passes information into the callback method. BeginInvoke returns an IAsyncResult, which can be used to monitor the progress of the asynchronous call. After calling BeginInvoke you can do the following:

  • Do some work and then call EndInvoke to block until the call completes.
  • Obtain a WaitHandle and use its WaitOne method to block execution until the WaitHandle is signaled, and then call EndInvoke.
  • Poll the IAsyncResult returned by BeginInvoke to determine when the asynchronous call has completed, and then call EndInvoke.
  • Pass a delegate for a callback method to BeginInvoke. The method is executed on a ThreadPool thread when the asynchronous call completes. The callback method calls EndInvoke.
  • Always call EndInvoke to complete your asynchronous call.

    Executing a Callback Method When an Asynchronous Call Completes

    Now for example we want to kill some process on seprate thread and on complete task we want to call another method to update UI. Whole process will complete without blocking our main Thread, so UI will be remain responsive all time.

    new Action(KillProcess)
    	.BeginInvoke(new AsyncCallback(OnKillProcessComplete), null);				
    private void KillProcess()
        	foreach (Process p in Process.GetProcessesByName("notepad"))
        catch { }
    private void OnKillProcessComplete(IAsyncResult result)
    	SetMessage("Process killed ...");            

    SetMessage update UI, For information how to update cross thread UI check following link.

    Cross Thread Update UI | .Net

    Related Tags


    32 Tutorials
    27 Snippets
    6 Products


    Contact Us

    Contact us

    Stay Connected