2012-11-28 58 views
0

我目前做给WCF调用的方法是沼泽标准事件,异步样式(例如)异步WCF调用与MonoDroid的

foo.EventArgs += Foo_EventArgsCompleted 
foo.EventArgsAsync(params...) 

这工作得很好,但可怕有时慢,也是很麻烦的然后你需要另一种方法来处理结果。

有没有一种方法可以更接近它在Win8上完成的方式?

private async foo<bool>() 
{ 
    try 
    { 
    await foo.EventArgsAsync(params...) 
    } 
    catch 
    { 
    // catch here 
    } 

    // deal with the code back 
    return true; 
} 

感谢

保罗

回答

0

你可以write your own *TaskAsync extension methods

如果您的代理有*Begin/*End方法,你可以使用TaskFactory.FromAsync

public static Task<int> FooTaskAsync(this FooClient client) 
{ 
    return Task<int>.Factory.FromAsync(client.BeginFoo, client.EndFoo, null); 
} 

否则,您必须使用TaskCompletionSource

public Task<int> FooTaskAsync(this FooClient client) 
{ 
    var tcs = new TaskCompletionSource<int>(); 
    client.FooCompleted += (s, e) => 
    { 
    if (e.Error != null) tcs.SetException(e.Error); 
    else if (e.Cancelled) tcs.SetCanceled(); 
    else tcs.SetResult(e.Result); 
    }; 
    client.FooAsync(); 
    return tcs.Task; 
} 
+0

感谢。这对我原来的方式会有什么很大的速度差异吗? – Nodoid

+0

不可以。您正在与另一个包装一个异步API;如果有的话,它会慢一点。好处是'基于任务的API可以与'async'无缝地使用,所以你的代码更加清晰。 –