- 通过SvcUtil /async 直接生产异步代理;
- 通过添加应用的方式,点击”添加引用“的“高级”按钮,在弹出来的对话框中选择“生成异步”。如图:
生成的异步调用代理类部分借口:
public System.IAsyncResult BeginAdd(int x, int y, System.AsyncCallback callback, object asyncState) {
return base.Channel.BeginAdd(x, y, callback, asyncState);
}
public void AddAsync(int x, int y) {
this.AddAsync(x, y, null);
}
public void AddAsync(int x, int y, object userState) {
if ((this.onBeginAddDelegate == null)) {
this.onBeginAddDelegate = new BeginOperationDelegate(this.OnBeginAdd);
}
if ((this.onEndAddDelegate == null)) {
this.onEndAddDelegate = new EndOperationDelegate(this.OnEndAdd);
}
if ((this.onAddCompletedDelegate == null)) {
this.onAddCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnAddCompleted);
}
base.InvokeAsync(this.onBeginAddDelegate, new object[] {
x,
y}, this.onEndAddDelegate, this.onAddCompletedDelegate, userState);
}
1、客户端异步调用服务
客户端异步调用服务主要方式有几种:
测试代码如下:
{
Console.WriteLine(i);
}
int resul = calculatorClient.EndAdd(asyncResult);
Console.WriteLine(string.Format("计算结果:{0}",resul));
{
for (int i = 0; i < 20; i++)
{
Console.WriteLine(i);
}
Console.WriteLine("开始计算...");
return x + y;
}
服务端输出如下:
客户端输出如下:
{
Console.WriteLine(i);
}
Thread.Sleep(5000);
Console.WriteLine("开始计算...");
return x + y;
delegate(IAsyncResult asyncResult)
{
int [] array = asyncResult.AsyncState as int [];
int result= calculatorClient.EndAdd(asyncResult1);
calculatorClient.close()
Console.WriteLine(string.Format("{0}+{1}={2}", array[0], array[1], result));
}, new []{1,2});
这种方式是对服务的异步调用完成以后,自动调用回调来获取结果。
calculatorClient.AddAsync(10, 36, new[] { 1000 });
//为异步调用完成定义触发事件
calculatorClient.AddCompleted += calculatorClient_AddCompleted;
Console.WriteLine("服务调用完成...");
Console.ReadKey();
//异步调用完成后执行
privatestaticvoid calculatorClient_AddCompleted(object obj, AddCompletedEventArgs args)
{
var array = args.UserState as int[];
int result = args.Result;
Console.WriteLine(result);
}
将服务定义为异步服务,契约定义如下 :
IAsyncResult BeginCalculator
(int x,int y ,AsyncCallback asyncCallback, object state);
void EndCalculator(IAsyncResult);
然后在实现契约接口的服务中,将方法实现为异步的。