我需要使用第三方异步网络服务。
一个特定服务应该返回一个字符串。我是从一个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安卓应用程序:
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
}
我不明白为什么Body
是null
编辑:我也尝试过这种方式:
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;
}
但我得到了同样的错误。
答案 0 :(得分:0)
搞定了
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;
};
这是最佳做法吗?