Practical C#9 - Simple Asynchronous Implementations

2 ways I came up with implementing “fire-and-forget” asynchronous calls:

Method 1:

using System.Threading;
...

//might be binded in a button-click

protected void but_click(object sender, eventArgs e)

{

    if (ThreadPool.QueueUserWorkItem(new WaitCallback(myLongRunningMethod), "abc"))

            txtResult.Text = "sucess";

}

private void myLongRunningMethod(object sender)

{

    //long running method, could be a long database query/update, etc

}

 

Method 2:

<%@ Page
Language="C#"

< ... >
Async
="True"
%>

protected delegate void myAsyncTaskDelegate();
private myAsyncTaskDelegate _func;

public IAsyncResult CustomBeginHandler(object sender, EventArgs e, AsyncCallback cb, object state)
{
_func = new myAsyncTaskDelegate(longMethod);
IAsyncResult ar = _func.BeginInvoke(cb, state);
return ar;
}

private void longMethod()
{
//..long operation here
}

public void CustomEndHandler(IAsyncResult ar)
{
_func.EndInvoke(ar);
}

Calling the asynchronous task delegates would mean making a function invocation call AddOnPreRenderCompleteAsync(new BeginEventHandler(CustomBeginHandler), new EndEventHandler(CustomEndHandler));  probably in the Page_Load or a Button_ClickEvent.

The method is documented here and with further references.

 

 

Published 07-12-2009 7:56 AM by avcajipe
Filed under: ,