繁体   English   中英

C#使用返回值调用异步Web服务

[英]c# call async web service with return value

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

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

Web服务工作正常,我在Soap UI上对其进行了测试,并且返回是有效的(它具有两个字符串参数,一个是请求,另一个是字符串返回值)。

这是我在核心可移植库上创建服务访问权的方式:

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;
}

但是我遇到了同样的错误。

得到它了

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;
    };

这是最佳做法吗?

暂无
暂无

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

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