Adding OperationContextScope to asynchronous methods

Posted on November 18, 2010 by

1


OperationContextScope is usually added in order to add additional information (such as headers) on outgoing requests from the client side.

It has two constructors:

OperationContextScope(IContextChannel)

OperationContextScope(OperationContext)

All samples found on the web provide code samples only for cases where the methods on the client side are synchronous, but what if the client API is asynchronous?

For this case we will have to use both of the OperationContextScope constructors. In the BeginXXX, the first constructor which receives the IContextChannel will be used. Then we will pass the created OperationContext.Current in the state parameter of the asynchronous call, and use it as a parameter for the second OperationContextScope constructor in the EndXXX. The code sample below illustrates this:

void OnBegin(object sender,EventArgs e)
{
    int sum = m_Proxy.Add(2,3);
    using (new OperationContextScope((IContextChannel)m_Proxy))
    {
         var httpRequestProperty = new HttpRequestMessageProperty();
         httpRequestProperty.Headers.Add(HttpRequestHeader.Cookie, Guid.NewGuid().ToString());
         OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] =
                 httpRequestProperty;
         m_Proxy.BeginAdd(2, 3, OnCompletion, OperationContext.Current);
     }
  }

void OnCompletion(IAsyncResult result)
{
    int sum;
    var context = result.AsyncState as OperationContext;
    using (new OperationContextScope(context))
    {
         sum = m_Proxy.EndAdd(result);
    }
    MessageBox.Show("Sum = " + sum);
}

The way to implement OperationContextScope for synchronous  requests is as follows:

 

using (new OperationContextScope((IContextChannel)m_Proxy))
{
    var httpRequestProperty = new HttpRequestMessageProperty();
   httpRequestProperty.Headers.Add(HttpRequestHeader.Cookie, Guid.NewGuid().ToString());
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] =
           httpRequestProperty;
    m_Proxy.BeginAdd(2, 3, OnCompletion, OperationContext.Current);
}

Advertisements
Posted in: General