WCF - 关于任务WCF的新手问题;

时间:2011-06-04 16:38:21

标签: multithreading wcf

这是WCF内部任务的最佳方法吗?

var tsk1 = Task.Factory.StartNew<list<object>>(()=> {

  Mysvc svc1 = new Mysvc();
  var t = svc1.getData();
  scv1.Close();
   return t;
});
var tsk2 = Task.Factory.StartNew<list<object>>(()=> {

  Mysvc svc1 = new Mysvc();
  var t2 = svc1.getData();
  scv1.Close();
   return t2;
});


Task.WaitALL(tsk1,tsk2);

var res = tsk1.Result;
var res2 = tsk2.Result;

非常感谢

1 个答案:

答案 0 :(得分:2)

如果您有合同的异步版本(如果您使用的是svcutil或添加服务引用,则可以通过指定正确的选项),您可以使用Task.Factory.FromAsync方法来执行此操作好:

public class StackOverflow_6237996
{
    [ServiceContract(Name = "ITest")]
    public interface ITest
    {
        [OperationContract]
        int Add(int x, int y);
    }
    [ServiceContract(Name = "ITest")]
    public interface ITestAsync
    {
        [OperationContract(AsyncPattern = true)]
        IAsyncResult BeginAdd(int x, int y, AsyncCallback callback, object userState);
        int EndAdd(IAsyncResult asyncResult);
    }
    public class Service : ITest
    {
        public int Add(int x, int y)
        {
            Thread.Sleep(100);
            return x + y;
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
        host.Open();
        Console.WriteLine("Host opened");

        ChannelFactory<ITestAsync> factory = new ChannelFactory<ITestAsync>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
        ITestAsync proxy = factory.CreateChannel();

        var tsk1 = Task.Factory.FromAsync<int>(
            proxy.BeginAdd(4, 5, null, null),
            (ar) => proxy.EndAdd(ar));
        var tsk2 = Task.Factory.FromAsync<int>(
            proxy.BeginAdd(7, 8, null, null),
            (ar) => proxy.EndAdd(ar));

        Task.WaitAll(tsk1, tsk2);

        Console.WriteLine("Result 1: {0}", tsk1.Result);
        Console.WriteLine("Result 2: {0}", tsk2.Result);

        ((IClientChannel)proxy).Close();
        factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}