WCF 异步调用
说明: WCF客户端异步调用与服务端代码没有关系,只是和客户端的代码有关系。
服务端
服务接口:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace ConsoleAsyService
{
/// <summary>
///
/// 测试异步运算器的接口
///
/// </summary>
[ServiceContract]
interface ICaculator
{
/// <summary>
/// 模拟异步统计的方法
/// </summary>
/// <returns></returns>
[OperationContract(IsOneWay=false)]
int Count();
}
}
服务实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleAsyService
{
public class Caculator:ICaculator
{
#region ICaculator 成员
public int Count()
{
Console.WriteLine("receive call {0}", DateTime.Now);
Thread.Sleep(10000);
Console.WriteLine("send result {0}", DateTime.Now);
return 100;
}
#endregion
}
}
客户端
调用过程
1. 添加服务引用
2. 设置服务引用
选中生成异步操作的复选按钮,系统默认的没选中,单击确定按钮,生成异步客户端调用代码。
代码
生成的客户端异步调用代码如下:
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行库版本:2.0.50727.1433
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace WCFTest.AsyCaculator {
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="AsyCaculator.ICaculator")]
public interface ICaculator {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ICaculator/Count", ReplyAction="http://tempuri.org/ICaculator/CountResponse")]
int Count();
[System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://tempuri.org/ICaculator/Count", ReplyAction="http://tempuri.org/ICaculator/CountResponse")]
System.IAsyncResult BeginCount(System.AsyncCallback callback, object asyncState);
int EndCount(System.IAsyncResult result);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public interface ICaculatorChannel : WCFTest.AsyCaculator.ICaculator, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class CountCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
private object[] results;
public CountCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
base(exception, cancelled, userState) {
this.results = results;
}
public int Result {
get {
base.RaiseExceptionIfNecessary();
return ((int)(this.results[0]));
}
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
public partial class CaculatorClient : System.ServiceModel.ClientBase<WCFTest.AsyCaculator.ICaculator>, WCFTest.AsyCaculator.ICaculator {
private BeginOperationDelegate onBeginCountDelegate;
private EndOperationDelegate onEndCountDelegate;
private System.Threading.SendOrPostCallback onCountCompletedDelegate;
public CaculatorClient() {
}
public CaculatorClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public CaculatorClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public CaculatorClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public CaculatorClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
public event System.EventHandler<CountCompletedEventArgs> CountCompleted;
public int Count() {
return base.Channel.Count();
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public System.IAsyncResult BeginCount(System.AsyncCallback callback, object asyncState) {
return base.Channel.BeginCount(callback, asyncState);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int EndCount(System.IAsyncResult result) {
return base.Channel.EndCount(result);
}
private System.IAsyncResult OnBeginCount(object[] inValues, System.AsyncCallback callback, object asyncState) {
return this.BeginCount(callback, asyncState);
}
private object[] OnEndCount(System.IAsyncResult result) {
int retVal = this.EndCount(result);
return new object[] {
retVal};
}
private void OnCountCompleted(object state) {
if ((this.CountCompleted != null)) {
InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
this.CountCompleted(this, new CountCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
}
}
public void CountAsync() {
this.CountAsync(null);
}
public void CountAsync(object userState) {
if ((this.onBeginCountDelegate == null)) {
this.onBeginCountDelegate = new BeginOperationDelegate(this.OnBeginCount);
}
if ((this.onEndCountDelegate == null)) {
this.onEndCountDelegate = new EndOperationDelegate(this.OnEndCount);
}
if ((this.onCountCompletedDelegate == null)) {
this.onCountCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnCountCompleted);
}
base.InvokeAsync(this.onBeginCountDelegate, null, this.onEndCountDelegate, this.onCountCompletedDelegate, userState);
}
}
}
客户端调用代码:
Console.WriteLine("begin asyCall {0}", DateTime.Now);
AsyCaculator.CaculatorClient asyCaculatorClient = new WCFTest.AsyCaculator.CaculatorClient();
asyCaculatorClient.CountCompleted += new EventHandler<WCFTest.AsyCaculator.CountCompletedEventArgs>(asyCaculatorClient_CountCompleted);
asyCaculatorClient.CountAsync();
Console.WriteLine("end asyCall{0}", DateTime.Now);
Console.Read();
调用完成后出发的事件:
static void asyCaculatorClient_CountCompleted(object sender, WCFTest.AsyCaculator.CountCompletedEventArgs e)
{
Console.WriteLine("Result={0},{1}", e.Result, DateTime.Now);
}
服务端运行结果:
客户端运行结果:
注意结果输出的顺序。