如何将SynchronizationContext与WCF一起使用

时间:2014-07-10 22:57:00

标签: wcf synchronizationcontext

我正在阅读SynchronizationContext并试图通过尝试将OperationContext传递给所有线程来确保我没有弄乱任何内容,即使在await调用之后也是如此。

我有这个SynchronizationContext课程:

public class OperationContextSynchronizationContext : SynchronizationContext
{

    // Track the context to make sure that it flows through to the next thread.

    private readonly OperationContext _context;

    public OperationContextSynchronizationContext(OperationContext context)
    {
        _context = context;
    }

    public override void Post(SendOrPostCallback d, object state)
    {
        OperationContext.Current = _context;
        d(state);
    }
}

然后围绕每个方法调用(使用Ninject IInterceptor)这样调用:

var original = SynchronizationContext.Current;
try
{
    // Make sure that the OperationContext flows across to the other threads,
    // since we need it for ContextStack.  (And also it's cool to have it.)
    SynchronizationContext.SetSynchronizationContext(new OperationContextSynchronizationContext(OperationContext.Current));

    // Process the method being called.
    invocation.Proceed();
}
finally
{
    SynchronizationContext.SetSynchronizationContext(original);
}

它似乎工作(我可以根据需要使用OperationContext),但这是正确的方法吗?我错过了一些可能会在以后咬我的重要事情吗?

编辑与Stephen Cleary的一些评论:

public class OperationContextSynchronizationContext : SynchronizationContext, IDisposable
{

    // Track the context to make sure that it flows through to the next thread.

    private readonly OperationContext _context;
    private readonly SynchronizationContext _previous;

    public OperationContextSynchronizationContext(OperationContext context)
    {
        _context = context;
        _previous = SynchronizationContext.Current;
        SynchronizationContext.SetSynchronizationContext(this);
    }

    public override void Post(SendOrPostCallback d, object state)
    {
        OperationContext.Current = _context;
        d(state);
        //(_previous ?? new SynchronizationContext()).Post(d, state);
    }

    private bool _disposed = false;
    public void Dispose()
    {
        if (!_disposed)
        {
            SynchronizationContext.SetSynchronizationContext(_previous);
            _disposed = true;
        }
    }
}

FINAL

public class OperationContextSynchronizationContext : SynchronizationContext, IDisposable
{

    // Track the operation context to make sure that it flows through to the next call context.

    private readonly OperationContext _context;
    private readonly SynchronizationContext _previous;

    public OperationContextSynchronizationContext()
    {
        _context = OperationContext.Current;
        _previous = SynchronizationContext.Current;
        SynchronizationContext.SetSynchronizationContext(this);
    }

    public override void Post(SendOrPostCallback d, object state)
    {
        var context = _previous ?? new SynchronizationContext();
        context.Post(
            s =>
            {
                OperationContext.Current = _context;
                try
                {
                    d(s);
                }
                catch (Exception ex)
                {
                    // If we didn't have this, async void would be bad news bears.
                    // Since async void is "fire and forget," they happen separate
                    // from the main call stack.  We're logging this separately so
                    // that they don't affect the main call (and it just makes sense).

                    // log here
                }
            },
            state
        );
    }

    private bool _disposed = false;
    public void Dispose()
    {
        if (!_disposed)
        {
            // Return to the previous context.
            SynchronizationContext.SetSynchronizationContext(_previous);
            _disposed = true;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

注意:在认为这是适合您的解决方案之前,请先阅读Stephen Cleary's answer。在我的特定用例中,除了在框架级别解决此问题之外,我没有任何其他选择。

所以,要将我的实现添加到混合... 我需要在await关键字之后修复OperationContext.Current和Thread.CurrentUICulture的流程,并且我发现在某些情况下你的解决方案无法正常工作(获胜的TDD!)。

这是新的SynchronisationContext,它将有助于捕获和恢复某些自定义状态:

public class CustomFlowingSynchronizationContext : SynchronizationContext
{
    private readonly SynchronizationContext _previous;
    private readonly ICustomContextFlowHandler _customContextFlowHandler;

    public CustomFlowingSynchronizationContext(ICustomContextFlowHandler customContextFlowHandler, SynchronizationContext synchronizationContext = null)
    {
        this._previous = synchronizationContext ?? SynchronizationContext.Current;
        this._customContextFlowHandler = customContextFlowHandler;
    }

    public override void Send(SendOrPostCallback d, object state)
    {
        var callback = this.CreateWrappedSendOrPostCallback(d);
        if (this._previous != null) this._previous.Send(callback, state);
        else base.Send(callback, state);
    }

    public override void OperationStarted()
    {
        this._customContextFlowHandler.Capture();
        if (this._previous != null) this._previous.OperationStarted();
        else base.OperationStarted();
    }

    public override void OperationCompleted()
    {
        if (this._previous != null) this._previous.OperationCompleted();
        else base.OperationCompleted();
    }

    public override int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout)
    {
        if (this._previous != null) return this._previous.Wait(waitHandles, waitAll, millisecondsTimeout);
        return base.Wait(waitHandles, waitAll, millisecondsTimeout);
    }

    public override void Post(SendOrPostCallback d, object state)
    {
        var callback = this.CreateWrappedSendOrPostCallback(d);
        if (this._previous != null) this._previous.Post( callback, state);
        else base.Post( callback, state);
    }
    private SendOrPostCallback CreateWrappedSendOrPostCallback(SendOrPostCallback d)
    {
        return s =>
        {
            var previousSyncCtx = SynchronizationContext.Current;
            var previousContext = this._customContextFlowHandler.CreateNewCapturedContext();
            SynchronizationContext.SetSynchronizationContext(this);
            this._customContextFlowHandler.Restore();
            try
            {
                d(s);
            }
            catch (Exception ex)
            {
                // If we didn't have this, async void would be bad news bears.
                // Since async void is "fire and forget", they happen separate
                // from the main call stack.  We're logging this separately so
                // that they don't affect the main call (and it just makes sense).
            }
            finally
            {
                this._customContextFlowHandler.Capture();
                // Let's get this thread back to where it was before
                SynchronizationContext.SetSynchronizationContext(previousSyncCtx);
                previousContext.Restore();
            }
        };
    }

    public override SynchronizationContext CreateCopy()
    {
        var synchronizationContext = this._previous != null ? this._previous.CreateCopy() : null;
        return new CustomFlowingSynchronizationContext(this._customContextFlowHandler, synchronizationContext);
    }

    public override string ToString()
    {
        return string.Format("{0}({1})->{2}", base.ToString(), this._customContextFlowHandler, this._previous);
    }
}

ICustomContextFlowHandler接口如下所示:

public interface ICustomContextFlowHandler
{
    void Capture();
    void Restore();
    ICustomContextFlowHandler CreateNewCapturedContext();
}

在WCF中为我的用例实现此ICustomContextFlowHandler如下:

public class WcfContextFlowHandler : ICustomContextFlowHandler
{
    private CultureInfo _currentCulture;
    private CultureInfo _currentUiCulture;
    private OperationContext _operationContext;

    public WcfContextFlowHandler()
    {
        this.Capture();
    }

    public void Capture()
    {
        this._operationContext = OperationContext.Current;
        this._currentCulture = Thread.CurrentThread.CurrentCulture;
        this._currentUiCulture = Thread.CurrentThread.CurrentUICulture;
    }

    public void Restore()
    {
        Thread.CurrentThread.CurrentUICulture = this._currentUiCulture;
        Thread.CurrentThread.CurrentCulture = this._currentCulture;
        OperationContext.Current = this._operationContext;
    }

    public ICustomContextFlowHandler CreateNewCapturedContext()
    {
        return new WcfContextFlowHandler();
    }
}

这是您需要添加到配置中以连接新SynchronisationContext的WCF行为(所有捆绑到一起以简化操作): (神奇的事情发生在AfterReceiveRequest方法中)

    public class WcfSynchronisationContextBehavior : BehaviorExtensionElement, IServiceBehavior, IDispatchMessageInspector
{
    #region Implementation of IServiceBehavior

    /// <summary>
    /// Provides the ability to change run-time property values or insert custom extension objects such as error handlers, message or parameter interceptors, security extensions, and other custom extension objects.
    /// </summary>
    /// <param name="serviceDescription">The service description.</param><param name="serviceHostBase">The host that is currently being built.</param>
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
        {
            foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
            {
                if (IsValidContractForBehavior(endpointDispatcher.ContractName))
                {
                    endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
                }
            }
        }
    }

    /// <summary>
    /// Provides the ability to inspect the service host and the service description to confirm that the service can run successfully.
    /// </summary>
    /// <param name="serviceDescription">The service description.</param><param name="serviceHostBase">The service host that is currently being constructed.</param>
    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        // No implementation
    }

    /// <summary>
    /// Provides the ability to pass custom data to binding elements to support the contract implementation.
    /// </summary>
    /// <param name="serviceDescription">The service description of the service.</param>
    /// <param name="serviceHostBase">The host of the service.</param><param name="endpoints">The service endpoints.</param>
    /// <param name="bindingParameters">Custom objects to which binding elements have access.</param>
    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
        Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {
        // No implementation
    }


    #endregion

    #region Implementation of IDispatchMessageInspector

    /// <summary>
    /// Called after an inbound message has been received but before the message is dispatched to the intended operation.
    /// </summary>
    /// <returns>
    /// The object used to correlate state. This object is passed back in the <see cref="M:System.ServiceModel.Dispatcher.IDispatchMessageInspector.BeforeSendReply(System.ServiceModel.Channels.Message@,System.Object)"/> method.
    /// </returns>
    /// <param name="request">The request message.</param><param name="channel">The incoming channel.</param><param name="instanceContext">The current service instance.</param>
    public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
    {
        var customContextFlowHandler = new WcfContextFlowHandler();
        customContextFlowHandler.Capture();
        var synchronizationContext = new CustomFlowingSynchronizationContext(customContextFlowHandler);
        SynchronizationContext.SetSynchronizationContext(synchronizationContext);
        return null;
    }

    /// <summary>
    /// Called after the operation has returned but before the reply message is sent.
    /// </summary>
    /// <param name="reply">The reply message. This value is null if the operation is one way.</param><param name="correlationState">The correlation object returned from the <see cref="M:System.ServiceModel.Dispatcher.IDispatchMessageInspector.AfterReceiveRequest(System.ServiceModel.Channels.Message@,System.ServiceModel.IClientChannel,System.ServiceModel.InstanceContext)"/> method.</param>
    public void BeforeSendReply(ref Message reply, object correlationState)
    {
        // No implementation
    }

    #endregion

    #region Helpers

    /// <summary>
    /// Filters out metadata contracts.
    /// </summary>
    /// <param name="contractName">The contract name to validate.</param>
    /// <returns>true if not a metadata contract, false otherwise</returns>
    private static bool IsValidContractForBehavior(string contractName)
    {
        return !(contractName.Equals("IMetadataExchange") || contractName.Equals("IHttpGetHelpPageAndMetadataContract"));
    }

    #endregion Helpers

    #region Overrides of BehaviorExtensionElement

    /// <summary>
    /// Creates a behavior extension based on the current configuration settings.
    /// </summary>
    /// <returns>
    /// The behavior extension.
    /// </returns>
    protected override object CreateBehavior()
    {
        return new WcfSynchronisationContextBehavior();
    }

    /// <summary>
    /// Gets the type of behavior.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Type"/>.
    /// </returns>
    public override Type BehaviorType
    {
        get { return typeof(WcfSynchronisationContextBehavior); }
    }

    #endregion
}

答案 1 :(得分:2)

有一些事情让我很突出。

首先,我建议不要使用SynchronizationContext。您正尝试使用框架解决方案解决应用程序问题。它会工作;我从架构的角度来看这个问题。但唯一的选择并不是那么干净:可能最合适的是为Task编写一个扩展方法,返回一个保留OperationContext的自定义awaiter。

其次,OperationContextSynchronizationContext.Post的实现直接执行委托。这有几个问题:首先,委托应该异步执行(我怀疑.NET框架或TPL中有一些地方假设这一点)。另一方面,这个SynchronizationContext有一个具体的实现;在我看来,如果自定义SyncCtx包装现有的更好。某些SyncCtx具有特定的线程要求,现在OperationContextSynchronizationContext充当替换而不是补充

第三,自定义SyncCtx在调用其委托时不会将自身设置为当前的SyncCtx。因此,如果您在同一方法中有两个await,则无效。