none
WCF 异步 RRS feed

  • 问题

  • 代码如下:

     服务器端:

    namespace WCFConsoleApplication
    {
     [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession)]
     public class FilesOne : Files
     {
      private const string baseLocation = @"D:\";
      private FileStream _stream;
      private byte[] _buffer;
      public string read(string fileName)
      {
       this._stream = new FileStream(baseLocation + fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
       this._buffer = new byte[this._stream.Length];
       this._stream.Read(this._buffer, 0, this._buffer.Length);
       this._stream.Close();
       return Encoding.ASCII.GetString(this._buffer)+"同步";
      }
    
      public IAsyncResult Beginread(string fileName, AsyncCallback userCallback, object stateObject)
      {
       try
       {
        this._stream = new FileStream(baseLocation + fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
        this._buffer = new byte[this._stream.Length];
        return this._stream.BeginRead(this._buffer, 0, this._buffer.Length, userCallback, stateObject);
       }
       catch (SystemException e)
       {
        FaultMessage ex = new FaultMessage();
        ex.Message = e.ToString();
        ex.ErrorCode = 001;
        throw new FaultException<FaultMessage>(ex, e.Message);
       }
      }
    
      public string Endread(IAsyncResult ar)
      {
       this._stream.EndRead(ar);
       this._stream.Close();
       return Encoding.ASCII.GetString(this._buffer)+"异步";
      }
     }
    
    
    
    }
    
    客户端:
    
    namespace WindowsForms
    {
      public delegate void ShowTextEventHander(string valStr);
      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
        }
    
        ServiceReference1.FilesClient cline;
        private void Form1_Load(object sender, EventArgs e)
        {
          cline = new ServiceReference1.FilesClient();
          cline.Beginread("Files.cs", callbackMethod, null);
        }
    
        void callbackMethod(IAsyncResult rs)
        {
          string str = cline.Endread(rs);
          rs.AsyncWaitHandle.Close();
          o_OnStepEvent(str);
        }
        public void o_OnStepEvent(string current)
        {
          if (richTextBox1.InvokeRequired)
          {
            this.Invoke(new ShowTextEventHander(this.o_OnStepEvent), new object[] { current });
          }
          else
          {
            richTextBox1.Text = current;
          }
        }
      }
    }
    
    请问一下 ,在我调试的时候,发现无论是同步还是异步执行的还是同步的方法,打印的内容显示是从同步的方法里取到的,请问这是为什么,是不是有什么地方写错了?谢谢。
    

    2011年4月17日 5:46

答案

  • 如果要实现服务端异步,你必须在 BeginXXX 操作上注明 OperationContract Async =true,同时必须把 XXX 方法上的 OperationContract 去掉.


    • 已标记为答案 my WCF 2011年4月18日 4:12
    2011年4月18日 2:48

全部回复