为什么没有执行开始方法和结束方法,然后在服务接口中定义同步操作?
下面是本文末尾的一个示例:http://www.danrigsby.com/blog/index.php/2008/03/26/async-operations-in-wcf-iasyncresult-model-server-side/
我添加了一些调试信息:
public double GetSquareRoot(double value)
{
System.Diagnostics.Debugger.Log(0, "MyService", "Get - Start\n");
Thread.Sleep(3000);
System.Diagnostics.Debugger.Log(0, "MyService", "Get - Finish\n");
return Math.Sqrt(value);
}
public IAsyncResult BeginGetSquareRoot(double value, AsyncCallback callback, object state)
{
System.Diagnostics.Debugger.Log(0, "MyService", "Begin - Start\n");
GetSquareRootAsyncResult asyncResult = new GetSquareRootAsyncResult(callback, state);
asyncResult.Value = value;
ThreadPool.QueueUserWorkItem(new WaitCallback((Callback)), asyncResult);
System.Diagnostics.Debugger.Log(0, "MyService", "Begin - Finish\n");
return asyncResult;
}
public double EndGetSquareRoot(IAsyncResult asyncResult)
{
System.Diagnostics.Debugger.Log(0, "MyService", "End - Start\n");
double result = 0;
using (GetSquareRootAsyncResult getSquareRootAsyncResult = asyncResult as GetSquareRootAsyncResult)
{
getSquareRootAsyncResult.AsyncWaitHandle.WaitOne();
result = getSquareRootAsyncResult.Result;
}
System.Diagnostics.Debugger.Log(0, "MyService", "End - Finish\n");
return result;
}对于原始代码,测试结果如下:
然后我从GetSquareRoot中删除IMyService方法,我得到了:
Finish
H 121End-
H 123结束-完成<代码>H 224<>F 225原因何在?
客户代码:
public partial class Form1 : Form
{
IMyService m_Client;
public Form1()
{
InitializeComponent();
ChannelFactory<IMyService> factory = new ChannelFactory<IMyService>("netTcp");
factory.Open();
m_Client = factory.CreateChannel();
}
private void button1_Click(object sender, EventArgs e)
{
double value = 0;
Double.TryParse(m_ValueTextBox.Text, out value);
m_Client.BeginGetSquareRoot(value, OnEndGetSquareRoot, null);
m_StartButton.Enabled = false;
m_ResultTextBox.Text = @"Loading...";
}
public void OnEndGetSquareRoot(IAsyncResult asyncResult)
{
this.Invoke(new MethodInvoker(delegate()
{
m_ResultTextBox.Text =
m_Client.EndGetSquareRoot(asyncResult).ToString();
m_StartButton.Enabled = true;
}));
}
}所描述的情况的不同之处在于IMyService接口.中没有声明GetSquareRoot。
发布于 2011-07-28 15:03:37
我以前看过那篇文章,但它错了。您是IMyService契约接口的服务器端版本,根本不应该有方法的同步定义。WCF dispatcher运行时将始终选择将消息映射到异步方法定义之上的同步方法定义。在这种情况下,您将不会与客户端共享原始的.NET服务契约接口,除非您还希望迫使客户端只能异步调用服务。
另外,请记住,客户机正在使用该方法的异步版本,这对服务器端来说绝对没有任何意义。它可能是一个运行在Linux上的Java服务,客户端都知道它在有线的另一端运行。客户端始终可以调用方法的同步或异步版本,但在服务端总是相同的。
发布于 2011-07-28 14:17:33
你说的是不同的方法。不使用异步方法实现同步方法。
https://stackoverflow.com/questions/6860228
复制相似问题