我需要返回一个从异步事件处理程序获得的字符串。我目前无法执行此操作,就好像我尝试返回处理程序内部一样,它给我一个错误,告诉我我不能返回任何对象,因为处理程序应该返回 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/错误信息?
最佳答案
您可以让该方法返回一个 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;
}
关于c# - 在异步事件处理程序中返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17792159/