WCF - A newbie question about Tasks an WCF ;
this is the best approach for WCF inside tasks ?;
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 you very much
If you have an asynchronous version of the contract (which, if you're using svcutil or add service reference, you can get by specifying the proper option), you can use the Task.Factory.FromAsync
method to do that as well:
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();
}
}
精彩评论