2011-06-04 46 views
0

這是WCF內部任務的最佳方法?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; 

Thnak你非常

回答

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(); 
    } 
} 
+0

謝謝卡洛斯,我給一個嘗試,讓你know..once再次感謝您的幫助 – user450191 2011-06-04 19:59:21