0

我有一个用于 silverlight/WP7 应用程序的异步回调函数,如下所示。

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

                    }
}

我希望能够使用回调函数以预先存在的方法返回数据值;IE

public List<Usernames> GetUsernames()
{
       List<Usernames> user_list = my_funtion();
       return user_list;
}

目前,我正在让回调函数更新触发事件的静态变量,并且使用大量数据并跟踪所有数据是一件令人讨厌的事情,尤其是当每个数据变量都需要自己的函数和静态变量时。

这样做的最佳方法是什么?

4

1 回答 1

0

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).

于 2012-11-28T21:37:54.530 回答