0

我正在寻找一个使用新的 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();
4

2 回答 2

1

你总是可以自己做:

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);
}
于 2012-11-06T21:08:41.733 回答
0

您必须使用目标版本 .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
于 2012-05-02T11:49:09.493 回答