与WCF客户端的并行请求

时间:2018-11-13 12:32:08

标签: c# wcf

我有具有相同接口的服务器服务器。我想使用WCF请求不同服务器的状态。我不想按顺序执行请求,因为这可能需要很长时间。因此,我将每个请求放到一个单独的线程中,将超时减少到2秒,等待所有线程完成并返回状态。

但是它仍然顺序执行。 WCF中必须有更深层次的内容,以阻止并行执行请求。或者我该怎么办?在网上搜寻了一天之后,我问你。请帮忙。

这是代码:

public class StateCollector {

private ChannelFactory<IMyService> channelFactory;
private readonly string myEndpointAddressTemplate = "http://{0}:14502/myservice";

public StateCollector(){
    //Instantiating the ChannelFactory is expensive, so we just have one.
    BasicHttpBinding binding = new BasicHttpBinding();
    channelFactory = new ChannelFactory<MyService>(binding);
}

public List<MyState> LoadStatus() {
    List<string> myAddresses = new List<string>(new []{"service1.xy", "service2.xy", "service3.xy" });

    List<Task<MyState>> tasks = new List<Task<MyState>>();
    List<MyState> results = new List<MyState>();

    //Start a thread for each address to get the state.
    foreach (string address in myAddresses) {
        Task<MyState> readState = ReadState(address);
        tasks.add(readState);
    }

    //Wait for all threads to finish and read results
    Task.WaitAll(tasks.ToArray());
    foreach (Task task in tasks) {
        results.Add(task.Result);
    }
    return results;
}

private Task<MyState> ReadState(string serviceAddress) {
    Task<MyState> readState = new Task<MyState>(() => {
        MyService myService = CreateMyService(serviceAddress);
        StateResponse stateResponse = null;
        MyState result = MyState.NOCONNECTION;
        try {
            //This call is blocking parallel execution!
            stateResponse = myService.GetState();
            result = stateResponse.State;
        } catch (System.Exception ignore) {
        } finally {
            ((IClientChannel)myService).Close();
        }
        return result;
    });
    readState.Start();
    return readState;
}

private MyService CreateMyService(string serviceAddress) {
    EndpointAddress endpointAddress = new EndpointAddress(string.Format(myEndpointAddressTemplate, serviceAddress));
    MyService myService = channelFactory.CreateChannel(endpointAddress);

    IClientChannel contextChannel = (IClientChannel) myService;
    contextChannel.OperationTimeout = TimeSpan.FromMilliseconds(2000);
    return myService;
}

}

0 个答案:

没有答案