这是一个C#问题,尽管代码是使用Xamarin iOS编写的。我想了解如何将Task方法与异步函数和回调委托相结合。所以在下面的代码示例中,我想调用等待ExecuteGetAsync()并等待SendAsynchronousRequest()完成。
private async Task<CustomHttpResponse> ExecuteGetAsync(CustomHttpRequest inRequest)
{
NSUrlConnection
.SendAsynchronousRequest(
(NSUrlRequest)request,
NSOperationQueue.MainQueue,
delegate(NSUrlResponse inResponse, NSData inData, NSError inError)
{
// Return the response somehow
});
}
答案 0 :(得分:2)
您应该使用TaskCompletionSource类,如下所示:
private Task<CustomHttpResponse> ExecuteGetAsync(CustomHttpRequest inRequest)
{
var tcs = new TaskCompletionSource<CustomHttpResponse>();
NSUrlConnection
.SendAsynchronousRequest(
(NSUrlRequest)request, //shouldn't this be inRequest?
NSOperationQueue.MainQueue,
delegate(NSUrlResponse inResponse, NSData inData, NSError inError)
{
bool error = ... //determine if we have an error
if(error)
tcs.SetException(new Exception(".. error message here ..")); //if we have an error, use the SetException method to set the exception for the Task
else
{
CustomHttpResponse result = ... // if we don't have an error, get result
tcs.SetResult(result); //set the result
}
});
return tcs.Task;
}
请注意,该方法不再使用async
关键字。
答案 1 :(得分:-1)
由于您可以访问父作用域,因此可以预先定义结果变量。然后,创建一个等待句柄。当您的代码获得最终响应时,您可以设置结果和句柄,代码会在主范围内返回结果。
private async Task<CustomHttpResponse> ExecuteGetAsync(CustomHttpRequest inRequest)
{
CustomHttpResponse result = null; // Put initial result here.
var handle = new AutoResetEvent(false);
NSUrlConnection
.SendAsynchronousRequest(
(NSUrlRequest)request,
NSOperationQueue.MainQueue,
delegate(NSUrlResponse inResponse, NSData inData, NSError inError)
{
// Return the response somehow
result = // make your result
handle.Set();
});
handle.WaitOne(10000) // Wait up to 10 seconds for result
return result;
}