我有一个用于 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
}
}
我希望能够使用回调函数在预先存在的方法中返回数据值;即
public List<Usernames> GetUsernames()
{
List<Usernames> user_list = my_funtion();
return user_list;
}
目前,我正在让回调函数更新静态变量,这会触发一个事件,并且处理大量数据并跟踪所有数据很麻烦,尤其是当每个数据变量都需要自己的函数和静态变量时。
最好的方法是什么?
救援任务!
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
}
我保留了一些//pay attention to this line
注释,以强调我从现有代码中添加的几行代码。
如果使用的是 C# 5.0,则可以在调用函数时await
结果。 如果您处于可以接受执行阻塞等待的上下文中,您可以立即对返回的任务使用 Result
(在某些环境中执行此操作时要小心),或者您可以使用返回任务的延续来处理结果(这是await
将在幕后执行的操作)。