为什么没有执行开始方法和结束方法,然后在服务接口中定义同步操作?
下面是本文末尾的一个示例: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 14:17:33
你说的是不同的方法。不使用异步方法实现同步方法。
https://stackoverflow.com/questions/6860228
复制相似问题