c#调用带有返回值的异步web服务

本文关键字:异步 web 服务 返回值 调用 | 更新日期: 2023-09-27 18:01:45

我需要使用第三方异步web服务。

一个特定的服务应该返回一个字符串。我是从xamarin android应用程序调用它的,我在一个核心可移植项目上创建了服务访问逻辑。

web服务工作得很好,我在Soap UI上测试了它,返回是有效的(它有两个字符串参数,一个请求和一个字符串返回值)。

这是我如何在core便携式库上创建服务访问:

public static async Task<string> GetResult(string param2)
{
    XSoapClient client = new XSoapClient();
    var result = await GetResultAsync(client, PARAM_1, param2);
    return result;
}
private static Task<string> GetResultAsync(this XSoapClient @this,
        string param1, string param2)
{
    var tcs = new TaskCompletionSource<string>();
    EventHandler<MyServiceCompletedEventArgs> callback = null;
    callback = (sender, args) =>
    {
        @this.MyServiceCompleted -= callback;
        if (args.Cancelled) tcs.TrySetCanceled();
        else if (args.Error != null) tcs.TrySetException(args.Error);
        else tcs.TrySetResult(args.Result);
    };
    @this.MyServiceCompleted += callback;
    @this.MyServiceAsync(param1, param2);
    return tcs.Task;
}

我是这样在客户端调用这个服务的——在这个例子中是xamarin android应用程序:

button.Click += async delegate
        {
            string param2 = p2EditText.Text;
            var result = await ServiceAccessLayer.GetResult(param2);
            resultEditText.Text = result;
        };

这会在这部分web服务代码上抛出一个异常:

[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    private string EndMyService(System.IAsyncResult result) {
        Core.ServiceReference.MyServiceResponse retVal = ((Core.ServiceReference.XSoap)(this)).EndMyService(result);
        return retVal.Body.MyServiceResult; // <= this line because Body is null
    }

我不明白为什么Bodynull

编辑:我也试过这样做:

public static void GetResult(string param2)
{
    XSoapClient client = new XSoapClient();
    client.MyServiceAsync(PARAM_1, param2);
    client.MyServiceCompleted += Client_MyServiceCompleted;
}
private static void Client_MyServiceCompleted(object sender, MyServiceCompletedEventArgs e)
{
    // do something with e.Result
    var result = e.Result;
}

c#调用带有返回值的异步web服务

明白了

private Task<string> MakeRequest()
{
    XSoapClient client = new XSoapClient();
    Task<string> request = Task.Factory.FromAsync(
        (callback, state) => c.BeginMyService(PARAM_1, param2, callback, state),
        result => c.EndMyService(result),
        TaskCreationOptions.None);
    Task<string> resultTask = request.ContinueWith(response =>
        {
            return response.Result;
        });
    return resultTask;
}
public async Task<string> GetResponse()
{
    var response = await MakeRequest();
    return response;
}

和android应用程序中的调用:

button.Click += async delegate
    {
        string param2 = p2EditText.Text;
        var result = await ServiceAccessLayer.GetResponse(param2);
        resultEditText.Text = result;
    };

这是最佳实践吗?