NetTcpBinding和async / await WCF阻塞

时间:2018-02-13 17:33:30

标签: c# wcf asynchronous async-await nettcpbinding

我们正在创建一个用于异步操作的共享WCF通道:

var channelFactory = new ChannelFactory<IWcfService>(new NetTcpBinding {TransferMode = TransferMode.Buffered});

channelFactory.Endpoint.Behaviors.Add(new DispatcherSynchronizationBehavior(true, 25));
var channel = channelFactory.CreateChannel(new EndpointAddress(new Uri("net.tcp://localhost:80/Service").AbsoluteUri + "/Test"));

这会调用以下服务:

[ServiceContract]
public interface IWcfService
{
    [OperationContract]
    Task<MyClass> DoSomethingAsync();
}

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)]
public class WcfServiceImpl : IWcfService
{
    public Task<MyClass> DoSomethingAsync()
    {
        Thread.Sleep(4000);

        return Task.FromResult(new MyClass());
    }
}

[Serializable]
public class MyClass
{
    public string SomeString { get; set; }      
    public MyClass Related { get; set; }        
    public int[] Numbers { get; set; }
}

如果我们一次启动3个请求并在响应上模拟一个长时间运行的任务:

        using ((IDisposable)channel)
        {
            var task1 = Task.Run(async () => await DoStuffAsync(channel));
            var task2 = Task.Run(async () => await DoStuffAsync(channel));
            var task3 = Task.Run(async () => await DoStuffAsync(channel));

            Task.WaitAll(task1, task2, task3);
        }
    }

    public static async Task DoStuffAsync(IWcfService channel)
    {
        await channel.DoSomethingAsync();

        Console.WriteLine("Response");

        // Simulate long running CPU bound operation
        Thread.Sleep(5000);

        Console.WriteLine("Wait completed");
    }

然后所有3个请求同时到达服务器,然后同时响应所有3个请求。

然而,一旦响应到达客户端,它就会依次处理每个响应。

Response
// 5 second delay
Wait completed
// Instant
Response
// 5 second delay
Wait completed
// Instant
Response

响应在不同的线程上恢复,但每次只运行1次。

如果我们使用流而不是缓冲我们得到预期的行为,客户端会同时处理所有3个响应。

我们尝试使用DispatcherSynchronizationBehaviour设置最大缓冲区大小,使用不同的并发模式,切换会话,ConfigureAwait false并明确调用channel.Open()

似乎没有办法在共享会话上获得适当的并发响应。

修改

我添加了一个我认为发生的图像,这个只发生在缓冲模式,在流模式下主线程不会阻塞。

3 threads spawn concurrently but responses are received in series for buffered mode

1 个答案:

答案 0 :(得分:3)

@Underscore

我最近试图解决完全相同的问题。虽然,我无法准确确定为什么TransferMode.Buffered导致WCF通道上的全局锁定,直到使用它的线程被释放,我发现了类似的问题{{3} }。他们提出了一种解决方法,即将RunContinuationsAsynchronously()添加到您的等待中,await channel.DoSomethingAsync().RunContinuationsAsynchronously() RunContinuationsAsynchronously()

public static class TaskExtensions
{
    public static Task<T> RunContinuationsAsynchronously<T>(this Task<T> task)
    {
        var tcs = new TaskCompletionSource<T>();

        task.ContinueWith((t, o) =>
        {
            if (t.IsFaulted)
            {
                if (t.Exception != null) tcs.SetException(t.Exception.InnerExceptions);
            }
            else if (t.IsCanceled)
            {
                tcs.SetCanceled();
            }
            else
            {
                tcs.SetResult(t.Result);
            }
        }, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);

        return tcs.Task;
    }

    public static Task RunContinuationsAsynchronously(this Task task)
    {
        var tcs = new TaskCompletionSource<object>();

        task.ContinueWith((t, o) =>
        {
            if (t.IsFaulted)
            {
                if (t.Exception != null) tcs.SetException(t.Exception.InnerExceptions);
            }
            else if (t.IsCanceled)
            {
                tcs.SetCanceled();
            }
            else
            {
                tcs.SetResult(null);
            }
        }, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);

        return tcs.Task;
    }
}

分隔WCF延续。显然Task.Yield()也有效。

实际了解为什么会发生这种情况会很好。