使用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代替替换字符串的思路来生成代码,有兴趣的自己参考代码.

源码

posted @ 2013-04-24 22:08  zhangweiwen  阅读(705)  评论(2编辑  收藏  举报