我创建了一个WCF服务,它使用Asynch模式异步执行冗长的操作。我在下面提到了在ServiceContract中实现BeginAddNumbers
和EndAddNumbers
方法的链接
http://aspalliance.com/1335_Asynchronous_Pattern_in_Windows_Communication_Foundation.5
一切都很好。但我不明白为什么我们需要这种方法?
Even though its asynchronous operation on server, client will still blocked and we have to invoke this operation asynchornously on client as well. So instead of implementing operation asynchronously on server it's always better to invoke operation asynchronously on client side to have responsive UI.
有谁能帮我理解在服务器端实现异步操作的概念?我需要和AsyncPattern=true
一起玩OperationContract
的任何实际例子吗?
添加客户端代码。客户端使用WPF应用程序实现
private void button1_Click(object sender, RoutedEventArgs e)
{
MathOperationClient c = new MathOperationClient();
Task t = new Task(new Action(() =>
{
///Even if AddNumbers is is implemented as asynchronous operation
///second call to AddNumbers get chance only after completing below
///call.
///Note: AddNumbers method takes 10 sec to execute
int nResult = c.AddNumbers(2, 3);
this.Dispatcher.BeginInvoke(new Action(()=>{
label1.Content = nResult.ToString();
})
, null);
}));
t.Start();
Task t1 = new Task(new Action(() =>
{
///Below method is invoked only after executing first call ( above call with parameters 2 and 3 )
///in other words below call is blocked for 10 seconds.
///So what is advantage of implementing asynchronous AddNumbers method on server side?
int result = c.AddNumbers(5,5);
this.Dispatcher.BeginInvoke(new Action(() =>
{
label2.Content = result.ToString();
})
, null);
}));
t1.Start();
}
谢谢,Hemant
答案 0 :(得分:0)
this post有一些信息。
一般来说:
对于WCF,realproxy的类型为System.ServiceModel.Channels.ServiceChannelProxy。即使我们使用BeginInvoke调用它,此代理实现也会同步调用服务方法。 如果在代理上调用的方法以BeginXXX()开头并且使用[OperationContract(AsyncPattern = true)]属性进行修饰,则WCF仅发出异步调用。
答案 1 :(得分:0)
我喜欢实现此服务器端的想法;并通过相应地命名操作来清楚地表明这一点。毕竟,如果一个呼叫本质上是异步的,为什么要让客户选择?
另一个原因是可伸缩性:在服务器端执行将WCF调度程序线程的请求解耦。这意味着不会阻止WCF线程。
有关示例,请参阅here。
你甚至可以决定让它成为单向通话;并定期对客户进行民意调查;事实上,这是我最喜欢的方法。