I have an Asynchronous callback function for a silverlight/WP7 application that looks like the following.
public static my_function()
{
PostClient conn = new PostClient(POST);
conn.DownloadStringCompleted += (object sender2, DownloadStringCompletedEventArgs z) =>
{
if (z.Error == null)
{
//Process result
string data = z.Result;
//MessageBox.Show(z.Result);
//Convert Login value to true false
try
{ ... do stuff here
}
}
I want to be able to use the callback functions to return data values in pre-existing methods; i.e.
public List<Usernames> GetUsernames()
{
List<Usernames> user_list = my_funtion();
return user_list;
}
At the moment i am having the callback functions update static variables which triggers an event and is a nuisance working with alot of data and keeping track of it all, especially when every data variable needs its own function and static variable.
Whats the best method of doing this?
Tasks to the rescue!
I stuck in some
//pay attention to this linecomments to emphasize the few lines of code I added from your existing code.If you’re using C# 5.0 you can
awaiton the result when calling the function. If you’re in a context in which it’s acceptable to perform a blocking wait you can just useResulton the returned task right away (be careful when doing that in certain environments) or you could use continuations of the returned task to process results (which is whatawaitwill do behind the scenes).