user1370249
user1370249

Reputation: 1

calling asynchronous method in windows phone 7

Is there any way to use server methods not asynchronously in windows phone 7 application? I have a list of data. In foreach loop, send a request to server for each data but they are not completed in the order of my calling. How can i do that?

Upvotes: 0

Views: 251

Answers (2)

Shawn Kendrot
Shawn Kendrot

Reputation: 12465

Do not revert to synchronous ways simply because something appears to not work. There are many benefits to working in an asynchronous world. There are also some dangers. The key is knowing how to avoid those dangers. Here is an example using WebClient that will have harmful effects.

foreach (var item in items)
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += (sender, args) =>
        {
            item.Stuff = args.Result;
        };
    client.OpenReadAsync(new Uri("http://mydomain.com/stuff"));
}

When the client is returned, there is no guarantee that item is the same item that "created" the client request. This is known as "Access to modified closer". Which simply means you might be trying to modify something that doesn't exist anymore, or is not the same. The proper approach to this is to capture your item within the foreach like such:

foreach (var item in items)
{
    var internalItem = item;
    WebClient client = new WebClient();
    client.DownloadStringCompleted += (sender, args) =>
        {
            internalItem.Stuff = args.Result;
        };
    client.OpenReadAsync(new Uri("http://mydomain.com/stuff"));
}

This ensures that you are using the correct item because it has been captured within the scope of the foreach.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499790

I have a list of data. In foreach loop, send a request to server for each data but they are not completed in the order of my calling. How can i do that?

Well you can effectively make them synchronous - get rid of it being an actual foreach loop, and instead set up the appropriate asynchronous callbacks so that when the first response comes in, you send the second request, etc, until there are no more requests. (You might want to use a Queue<T> to queue up the requests to send.)

Upvotes: 2

Related Questions