【问题标题】:Looking for an example of using async for calling a web service in Silverlight?寻找在 Silverlight 中使用异步调用 Web 服务的示例?
【发布时间】:2012-05-07 18:19:18
【问题描述】:

我正在寻找一个使用新的 async 关键字在 Silverlight 中调用 Web 服务的示例。

这是我要转换的代码:

var client = new DashboardServicesClient("BasicHttpBinding_IDashboardServices", App.DashboardServicesAddress);
client.SelectActiveDealsCompleted += (s, e) => m_Parent.BeginInvoke(() => RefreshDealsGridComplete(e.Result, e.Error));
client.SelectActiveDealsAsync();

【问题讨论】:

    标签: silverlight visual-studio-2012 c#-5.0


    【解决方案1】:

    您必须使用目标版本 .Net 4.5 重新生成服务代码。然后您可以使用async 关键字。写一些这样的代码:

    var client = new DashboardServicesClient("BasicHttpBinding_IDashboardServices", App.DashboardServicesAddress);
    // Wait here until you get the result ...
    var result = await client.SelectActiveDealsAsync();
    // ... then refresh the ui synchronously.
    RefreshDealsGridComplete(result);
    

    或者您使用ContinueWith 方法:

    var client = new DashboardServicesClient("BasicHttpBinding_IDashboardServices", App.DashboardServicesAddress);
    // Start the call ...
    var resultAwaiter = client.SelectActiveDealsAsync();
    // ... and define, what to do after finishing (while the call is running) ...
    resultAwaiter.ContinueWith( async task => RefreshDealsGridComplete(await resultAwaiter));
    // ... and forget it
    

    【讨论】:

    • 没用,我仍然只看到非基于任务的版本。此外,“服务参考设置”对话框的“生成基于任务的操作”选项灰显。
    【解决方案2】:

    你总是可以自己做的:

    static class DashboardServicesClientExtensions
    {
        //typeof(TypeIDontKnow) == e.Result.GetType()
        public static Task<TypeIDontKnow>> SelectActiveDealsTaskAsync()
        {
            var tcs = new TaskCompletionSource<TypeIDontKnow>();
    
            client.SelectActiveDealsCompleted += (s, e) => m_Parent.BeginInvoke(() =>
            {
                if (e.Erorr != null)
                    tcs.TrySetException(e.Error);
                else
                    tcs.TrySetResult(e.Result);
            };
            client.SelectActiveDealsAsync();
    
            return tcs.Task;
        }
    };
    
    // calling code
    // you might change the return type to Tuple if you want :/
    try
    {
        // equivalent of e.Result
        RefreshDealsGridComplete(await client.SelectActiveDealsTaskAsync(), null);
    }
    catch (Exception e)
    {
        RefreshDealsGridComplete(null, e);
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 1970-01-01
      • 2023-03-15
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多