Roniu
Roniu

Reputation: 79

How to make Async call execute immediately when called?

I have a problem assigning a value with the help of a WebMethod. I have a method from where I call the WebMethod:

................
svc.GetNameCompleted += GetUserName;
svc.GetNameAsync(ordercode);

string name = MyName;
................

The problem is that the third line is executed first (string name = MyName;) and then the GetUserName() method.

In the GetUserName() method, I assign a value to MyName variable, but since this is called after (string name=MyName), the first time I execute the project, I got string name = null; since the MyName variable is null.

Upvotes: 0

Views: 101

Answers (3)

Mashton
Mashton

Reputation: 6415

You should only be be setting name once you have the name, which will take place in the method you've defined as GetUserName (not a great name for the GetNameCompleted handler though, so I've renamed it in example below)

public void SomeMethod()
{
  svc.GetNameCompleted += GetUserNameCompleted;
  svc.GetNameAsync(ordercode);
}

public void GetUserNameCompleted(whatever the signature is)
{
  string name = MyName;
}

Upvotes: 0

Alberto Solano
Alberto Solano

Reputation: 8227

As far as I know, you can't. All the web service calls in Silverlight are asynchronous. You cannot call an asynchronous method synchronously. You should capture the result in an asynchronous way and tell Silverlight what to do with it as soon as the method completed its execution.

I think you should write an EventHandler for your web method, in order to manage the completion of the method and handle the result.

Upvotes: 0

Bun
Bun

Reputation: 1495

Async methods should return a Task so that you can wait for its completion:

svc.GetNameCompleted += GetUserName;
Task<string> nameTask = svc.GetNameAsync(ordercode);

...

string name = await nameTask;

Upvotes: 1

Related Questions