Andrea Azzola

Tips and Techniques for Lifestyle Design

Call async methods with C#

Posted on [Permalink]

The article might be obsolete due to C# technology improvements

This article help you in delegating work to an asynchronous thread in C#, thus allowing for code execution and App responsitivity, but you might go a step futher implementing error notifications, polling, wait for the procedure to complete at a certain point… and so on.

Suppose you have the following method

public void UploadFile(string path)
{
	try
    {
        //... uploads some file to the server
    }
    catch(Exception ex)
    {
        // ... handle errors
    }
}

And you are implementing it as a web service: you are asked to give an immediate response and upload the file asynchronously, the user won't use soon, as she only needs the upload.

Declare a method delegate

public delegate void UploadFileDelegate(string path);

Invoke it asynchronously

[WebMethod]
public bool GetFile(string path)
{
	try
	{
		UploadFileDelegate uid = UploadFile;
		IAsyncResult rsl = uid.BeginInvoke(path, null, null);
		return true;
	}
	catch(Exception ex)
	{
		return false;
	}
}

The BeginInvoke method start the thread but allows for the code to execute further without waiting for an immediate return.

Categories: