在Silverlight中查找使用async调用Web服务的示例?

时间:2012-04-27 00:27:20

标签: silverlight visual-studio-2012 c#-5.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();

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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 Methode:

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