Invoking operations asynchronously with expiration

I have a classic asynchronous message dispatching problem. Essentially, I need to asynchronously dispatch messages and then capture the message response when the dispatch is complete. The problem is, I can't seem to figure out how to make any one request cycle self-expire and shortcircuit.

Here is a sample of the pattern I am using at the moment:

Defined delegate for invokation

private delegate IResponse MessageDispatchDelegate(IRequest request);

Dispatch messages with a callback

var dispatcher = new MessageDispatchDelegate(DispatchMessage);
dispatcher.BeginInvoke(requestMessage, DispatchMessageCallback, null);

Dispatch the message

private IResponse DispatchMessage(IRequest request)
{
  //Dispatch the message and throw exception if it times out
}

Get results of dispatch as either a response or an exception

private void DispatchMessageCallback(IAsyncResult ar)
{
  //Get result from EndInvoke(r) which could be IResponse or a Timeout Exception
}

What I can't figure out is how to cleanly implement the timeout/shortcircuit process in the DispatchMessage method. Any ideas would be appreciated

Answers


        var dispatcher = new MessageDispatchDelegate(DispatchMessage);

        var asyncResult = dispatcher.BeginInvoke(requestMessage, DispatchMessageCallback, null);
        if (!asyncResult.AsyncWaitHandle.WaitOne(1000, false))
        {
             /*Timeout action*/
        }
        else
        {
            response = dispatcher.EndInvoke(asyncResult);
        }

Need Your Help

Align images to the right of text in container

html css stylesheet

I am trying to align two icons (the facebook and google+ icons) of my website found here. These little round icons can be seen just below the navigation bar at the top. The navigation bar is part o...

How to handle deleted app device token in Pushwoosh?

java android ios push-notification pushwoosh

I am using Pushwoosh for sending notifications to Android and iOS apps from Java Webservices. I found it very easy to use.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.