John John
John John

Reputation: 1

How can i call two methods asynchronously?

I have the following two methods:

private static void webservicecalls()
{
   WebServiceOne();
   WebServiceTwo();
}

So how i can call these two methods asynchronously instead of waiting for the first web service call to be complete before calling the second web service?

Update:

Now both WebSericeOne and WebServiceTwo have sub calls such as:

private static void WebServiceOne()
{
    CallOne();
    CallThree();
}

private static void WebServiceTwo()
{
    CallTwo();
    CallFour();
}

so i need the call to have the following sequence for the sub calls :-

CallOne();
CallTwo();
CallThree();
CallFour();

Upvotes: 2

Views: 1935

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1064054

Depending on what are you using to implement webserviceone webservicetwo, it is quite likely that the web-service tooling itself will have full async support, so the first thing to do is: check that, and use the async API rather than the sync API.

If, for some reason, that does not exist - you could do something like:

var task = new Task(() => webservice1());
task.Start();
webservice2();
task.Wait();

(obviously you could run both fully async; I'm assuming in the above you just want to run them both in parallel, and "join" at the end)

Re your edit: if the order must be exactly "one","two","three","four", then you can't do them in parallel, so you would have to instead just run the entire thing in the background:

new Task(() => {
    webservice1();
    webservice2();
}).Start();

which will guarantee the execution order, sacrificing parallelism.

Upvotes: 5

Todd Richardson
Todd Richardson

Reputation: 1129

I like using an Action.

private static void WebServiceCalls()
{ 
    var someState = 3;
    Action a1 = () => { WebserviceOne(); };
    Action a2 = () => { WebserviceTwo(); };

    a1.BeginInvoke(WebServiceCallBack, someState); //see code section below
    a2.BeginInvoke(null, null); //fire and forget...

}

This also allows you to create a Callback for handling code:

void WebServiceCallBack(IAsyncResult result)
{
    int state = (int)result.AsyncState;
    //do more??
}

@Mark brings up a valid point: If you are working with a webservice within Visual studio, you can use the service reference configuration window to create the Channel Proxy class with async syntax. (I.e. with the BeginWebServiceOne and EndWebServiceOne which would preclude the need to create Async wrappers.)

Upvotes: 1

abatishchev
abatishchev

Reputation: 100348

Action one = () => WebServiceOne();
Action two = () => WebServiceTwo();
one.BeginInvoke(null, null);
two.BeginInvoke(null, null);

Upvotes: 2

Christian Phillips
Christian Phillips

Reputation: 18769

Take a look at the task library here, and the navigation for the sub categories on the left

http://msdn.microsoft.com/en-us/library/dd537609.aspx

Upvotes: 0

Related Questions