繁体   English   中英

NetTcpBinding和async / await WCF阻塞

[英]NetTcpBinding and async/await WCF blocking

我们正在创建一个共享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个线程同时生成,但响应是针对缓冲模式串行接收的

@Underscore

我最近试图解决完全相同的问题。 虽然,我无法准确确定为什么TransferMode.Buffered导致WCF通道上的全局锁定,直到使用它的线程被释放,我发现这个类似的问题在等待之后死锁 他们提出了一个解决方法,即将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()也可以。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM