我需要返回一个从异步事件处理程序获得的字符串。我目前不能这样做,就好像我试图在处理程序内部返回一样,这会给我一个错误,告诉我不能返回任何对象,因为处理程序应该返回void。
这是我的代码:
public String Login(String username, String password)
{
String returningData = "";
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("user", username);
parameters.Add("pass", password);
PostClient client = new PostClient(parameters);
client.DownloadStringCompleted += (senders, ex) =>
{
if (ex.Error == null)
{
//Process the result...
return ex.Result;
}
else
{
return "An error occurred. The details of the error: " + ex.Error;
}
};
client.DownloadStringAsync(new Uri("http://www.site.com/sample.php", UriKind.Absolute));
}
如何正确返回ex.Result/error消息?
您可以让方法返回Task<string>
而不是字符串。该方法在被调用时不会立即返回值,调用该方法将启动工作,任务可以在将来的某个时候完成。您可以使用TaskCompletionSource
创建要返回的任务。
public Task<string> Login(String username, String password)
{
var tcs = new TaskCompletionSource<string>();
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("user", username);
parameters.Add("pass", password);
PostClient client = new PostClient(parameters);
client.DownloadStringCompleted += (senders, ex) =>
{
if (ex.Error == null)
{
//Process the result...
tcs.TrySetResult(ex.Result);
}
else
{
string errorMessage = "An error occurred. The details of the error: " + ex.Error;
//todo use a more derived exception type
tcs.TrySetException(new Exception(errorMessage));
}
};
client.DownloadStringAsync(new Uri("http://inkyapps.mobilemp.net/scripts/PHP/socialnet/login.php", UriKind.Absolute));
return tcs.Task;
}
只需触发一个事件,即可通知"外部世界"操作完成。
为此,定义您的代理人:
public void delegate OnError(object sender, string message);
public event OnError OnErrorEvent;
...
client.DownloadStringCompleted += (senders, ex) =>
{
if (ex.Error == null)
{
//Process the result...
return ex.Result;
}
else
{
if(OnErrorEvent != null)
OnErrorEvent(this, "An error occurred. The details of the error: " + ex.Error;);
}
};
这只是一个例子,你必须为你的具体案例选择更合适的代表签名。
我会将其封装到Task<string>
中,并返回:
public Task<string> LoginAsync(String username, String password)
{
var results = new TaskCompletionSource<string>();
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("user", username);
parameters.Add("pass", password);
PostClient client = new PostClient(parameters);
client.DownloadStringCompleted += (senders, ex) =>
{
if (ex.Error == null)
{
results.TrySetResult(ex.Result);
}
else
{
results.TrySetException(ex.Error); // Set the exception
}
};
client.DownloadStringAsync(new Uri("http://inkyapps.mobilemp.net/scripts/PHP/socialnet/login.php", UriKind.Absolute));
return results.Task;
}
这将允许您直接将此方法与async
/await
关键字一起使用,从而在调用方中提供适当的异步支持和异常处理。