使用Task简化Silverlight调用Wcf(再续)

上一篇的工具生成方法有个致命缺点:当wcf的参数个数大于或者等于4时,将会报错,因为Task.Factory.FromAsync这个方法最多支持三个参数.

为了解决这个问题,临时的解决办法是配置生成服务引用时选择"始终生成消息合同",如下图.

image

虽然这样可暂时解决这个问题,但使用有了这个消息合同后使用非常不变,每次调用Wcf方法时总要new一个XXXRequest.

这个版本解决这个问题,解决思路如下:

对于这样一个Wcf方法:

public int Add(int a, int b, int c, int d, int e)
{}

多生成一个Request类:

public class AddRequest
{            
    public Int32 a { get; set; }
    public Int32 b { get; set; }
    public Int32 c { get; set; }
    public Int32 d { get; set; }
    public Int32 e { get; set; }
}

再多生成一个BeginXXX的方法代替Channel.BeginXXX:

private System.IAsyncResult BeginAdd(AddRequest request, AsyncCallback callback, Object asyncState)
{
    return Channel.BeginAdd(request.a, request.b, request.c, request.d, request.e, callback, asyncState);
}

这个适配方法用前面定义的Request类为参数,代替了原来有很多参数的Channel.Begin方法,然后在FromAsync里使用这个方法:

public Task<Int32> AddTaskAsync(int a, int b, int c, int d, int e)
{
    var request = new AddRequest();
    request.a = a;
    request.b = b;
    request.c = c;
    request.d = d;
    request.e = e;
    return Task<Int32>.Factory.FromAsync(BeginAdd, Channel.EndAdd, request, null);
}

很简单,先new一个Reuqest,再在FromAsync里使用前面的Begin方法(注意不是Channel.Begin),因为我们定义的Begin的方法只有一个参数,这样就绕过了,FromAsync最多只能有三个参数的问题.

这个版本还有一个改变就是使用CodeDom代替替换字符串的思路来生成代码,有兴趣的自己参考代码.

源码

转载于:https://www.cnblogs.com/lemontea/archive/2013/04/24/3041267.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值