简体   繁体   中英

C# - Asynchronous Callback - WP7 - Silverlight - Storing data

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; ie

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!

public static Task<List<Usernames>> my_function()
{
    var tcs = new TaskCompletionSource<List<Usernames>>(); //pay attention to this line

    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

                tcs.SetResult(null); //pay attention to this line
            }
            finally
            {
            }
        }
        else
        {
             //pay attention to this line
            tcs.SetException(new Exception());//todo put in real exception
        }
    };

    return tcs.Task; //pay attention to this line
}

I stuck in some //pay attention to this line comments to emphasize the few lines of code I added from your existing code.

If you're using C# 5.0 you can await on 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 use Result on 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 what await will do behind the scenes).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM