Question

My question is fairly simple, but I suspect the answer won't be. In my WP7 app, I am calling a REST web service to GET some data which I deserialize into class objects.

My request method and its AsyncCallBack method live inside a class (an MVVM ViewModel), and are invoked from inside an instance method on the class (LoadData).

The AsyncCallBack deserializes the json retrieved from the web service into an object. I need to add this object to a collection on the class where all of this is taking place - like so:

this.Collection1.Add(retrievedObject); 

Of course, since AsyncCallBack is static, I can't access the "this" keyword. I also can't return the retrievedObject to the caller, because the AsyncCallBack has to return void. I realize I'm probably the victim of some basic misunderstanding here. How do I solve this?

Thanks!

Was it helpful?

Solution

Does it have to be static? No.

The callback doesn't have to be static, but you are right to be concerned about thread safety. The callback method will be called on a different thread, so if it uses some data that the main thread is also using, you have to synchronise the access to that data.

Does it have to return void? Yes.

The callback method can't return anything to the method that has started the asynchronous task, because that method returns before the task is completed. For the callback method to set that return value, it would have to travel back in time.

OTHER TIPS

Read how to use the Asynchronous Programming Pattern (APM): msdn.microsoft.com/en-us/library/ms228963.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top