简体   繁体   English

如何在没有基于任务的代理的情况下处理Windows Phone 8中的服务引用

[英]How to handle Service References in Windows Phone 8 without Task-Based proxies

With so much emphasis on Task-Based asynchronous development, I was surprised to see that Service References in Windows Phone 8 do not support task-based implementations. 如此强调基于任务的异步开发,我惊讶地发现Windows Phone 8中的服务引用不支持基于任务的实现。 Instead they use a "XYZCompleted" event-based asynchronous approach. 而是使用基于事件的“ XYZCompleted”异步方法。

As a result, code like this is necessary: http://codepaste.net/fqyt47 结果,像这样的代码是必需的: http : //codepaste.net/fqyt47

public async Task<IEnumerable<MyService.Character>> GetCharactersAsync()
{
    var _Task = new TaskCompletionSource<IEnumerable<MyService.Character>>();
    var _Client = new MyService.ServiceClient();
    _Client.GetCharactersCompleted += (s, e) =>
    {
        var _Characters = e.Result as IEnumerable<MyService.Character>;
        if (e.Error != null && !_Task.TrySetException(e.Error))
            System.Diagnostics.Debugger.Break();
        else if (e.Cancelled && !_Task.TrySetCanceled())
            System.Diagnostics.Debugger.Break();
        else if (!_Task.TrySetResult(_Characters))
            System.Diagnostics.Debugger.Break();
    };
    _Client.GetCharactersAsync();

    return await _Task.Task;
}

However, this feels wrong . 但是, 这感觉不对 Is there a better, more elegant approach? 有没有更好,更优雅的方法?

I'm surprised Windows Phone 8 doesn't have Task -based reference creation. 我很惊讶Windows Phone 8没有基于Task的参考创建。

That said, TaskCompletionSource is the standard way of interoperating with various asynchronous patterns (including EAP) . 也就是说, TaskCompletionSource 是与各种异步模式(包括EAP)进行互操作的标准方法

Usually it's done with extension methods which are consumable by await but which are not async themselves: 通常,它是通过扩展方法来完成的,这些扩展方法可以由await消耗,但是它们本身并不async

public Task<IEnumerable<MyService.Character>> GetCharactersTaskAsync(this ServiceClient client)
{
  var tcs = new TaskCompletionSource<IEnumerable<MyService.Character>>();
  client.GetCharactersCompleted += (s, e) =>
  {
    if (e.Error != null) tcs.SetException(e.Error);
    else if (e.Cancelled) tcs.SetCanceled();
    else tcs.SetResult(e.Result);
  };
  client.GetCharactersAsync();
  return tcs.Task;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM