Posts

....
Technical Blog for .NET Developers ©

Sunday, October 28, 2012

Calling WCF Async

When our applications call a web service, either from desktop apps or web sites, we have to keep in mind its response times

There is a mechanism for calling the web service asynchronously. Let's take the example exposed in this link, WCF Services, and configure the service reference to generate asynchronous operations



There are two different ways to achieve the process

With the next code, we are assigning a handler to the GetElementsCompleted event, so the application will work on other tasks while is waiting for the event triggers

     
private void btnGetElements_Click(object sender, EventArgs e)
{
    try
    {
        client = new ChemicalServiceClient();
        client.GetElementsCompleted += 
         new EventHandler<GetElementsCompletedEventArgs>(client_GetElementsCompleted);
        client.GetElementsAsync();
    }
    catch (FaultException<AccessFault> ex)
    {
        lblResult.Text = ex.Message + ex.Detail.ExceptionType + ex.Detail.StackTrace;
    }
}

void client_GetElementsCompleted(object sender, GetElementsCompletedEventArgs e)
{
    dgvElements.DataSource = e.Result.ToList();
    lblResult.Text = e.Result.Length.ToString() + " elements were found";
}


The second way is an asynchronous call itself, with the implementation of a callback function, it generates a separated thread to manage the call

The code is as follows

     
private void btnInsertElement_Click(object sender, EventArgs e)
{
    try
    {
        client = new ChemicalServiceClient();
        Element elemToInsert = new Element()
        {
            AtomicSymbol = txtAtomicSymbol.Text,
            Name = txtName.Text,
            LatinName = txtLatinName.Text
        };

        client.BeginInsertElement(elemToInsert, InsertAsyncCallBack, null);
    }
    catch (FaultException<AccessFault> ex)
    {
        lblResult.Text = ex.Message + ex.Detail.ExceptionType + ex.Detail.StackTrace;
    }
}

private void InsertAsyncCallBack(IAsyncResult asyncResult)
{
    if (asyncResult.IsCompleted)
    {
        string elemKey = client.EndInsertElement(asyncResult);
        lblResult.Text = elemKey + " was added correctly";
    }
}


This second way is the recommended for web scenarios, because the site will renders immediatly after the function call, instead of wait for the event fires


<METHOD SOFTWARE © 2012>