【发布时间】:2016-02-26 09:03:53
【问题描述】:
我有这个项目: - 托管在控制台应用程序中的 WCF 服务 (basicHttpBinding) - 为我的合同分离 PCL 库 - WPF客户端 - Xamarin.Forms(便携式)- 三个移动客户端。
在 WCF 中,我有异步服务,我想在每个客户端中使用它。这是我的第一个问题:PCL 在客户端不支持 TAP(基于任务的异步模式)。在 PCL 中,我只能以 IAsyncResult Begin/End 样式执行 APM(异步编程模型)。让我展示一下我的代码:
这是我的 WCF 服务:
[ServiceContract]
public interface ICalculatorService
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginGetSum(int a, int b, AsyncCallback callback, object state);
string EndGetSum(IAsyncResult asyncResult);
}
public class CalculatorService : ICalculatorService
{
private Task<string> GetSum(int a, int b)
{
return Task.Factory.StartNew(() => (a+ b).ToString());
}
public IAsyncResult BeginGetSum(int a, int b, AsyncCallback callback, object state)
{
var tcs = new TaskCompletionSource<string>(state);
var task = GetSum(a, b);
task.ContinueWith(t =>
{
if (t.IsFaulted)
tcs.TrySetException(t.Exception.InnerExceptions);
else if (t.IsCanceled)
tcs.TrySetCanceled();
else
tcs.TrySetResult(t.Result);
if (callback != null)
callback(tcs.Task);
});
return tcs.Task;
}
public string EndGetSum(IAsyncResult asyncResult)
{
try
{
return ((Task<string>)asyncResult).Result;
}
catch (AggregateException ex)
{
throw ex.InnerException;
}
}
}
和主机配置:
<system.serviceModel>
<services>
<service name="MobileWCF.ServerHost.CalculatorService">
<endpoint address="http://localhost:9003/CalculatorService" binding="basicHttpBinding"
contract="MobileWCF.Contracts.ICalculatorService" />
</service>
</services>
</system.serviceModel>
在每个客户端(Xamarin.Froms 和 WPF)中,我都使用它,如下所示:
private void bConnect_Click(object sender, EventArgs e)
{
string strAddress = "http://localhost:9003/CalculatorService";
BasicHttpBinding httpBinding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress(strAddress);
ChannelFactory<ICalculatorService> channel = new ChannelFactory<ICalculatorService>(httpBinding, address);
var game = channel.CreateChannel(address);
var num = game.BeginGetSum(4, 1, Callback, game);
}
private void Callback(IAsyncResult result)
{
var res = result.AsyncState as ICalculatorService;
if (res != null)
Debug.Write(res.EndGetSum(result));
}
我的问题是: 在 WPF 或 WinForms 等客户端上,我想像这样使用它:
await service.GetSum(1, 2); async await 风格。
我的问题是:我应该如何实现我的 WCF 合同和服务实现,以便能够在 Xamarin.Forms 客户端的 Begin/End APM 样式和 WPF 中的 async-await TAP 样式中使用它还是 WinForms 程序?
【问题讨论】:
-
@Gusman 不能解决我的问题。我想将在服务中声明为 APM(带开始/结束)的异步方法调用为异步等待样式中的 TAP
-
pcl 上的 wcf 不支持等待,或者您在更改要共享的项目类型时使用了开始/结束模式。
标签: c# wpf wcf xamarin xamarin.forms