21

私はWinformsアプリケーションで次の問題を追跡しようとしています:
メインスレッドで実行さSynchronizationContext.Currentれるタスクの継続(つまり.ContinueWith)でnullです(現在の同期コンテキストはであると予想されますSystem.Windows.Forms.WindowsFormsSynchronizationContext)。

この問題を示すWinformsコードは次のとおりです。

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TaskScheduler ts = TaskScheduler.FromCurrentSynchronizationContext(); // Get the UI task scheduler

            // This line is required to see the issue (Removing this causes the problem to go away), since it changes the codeflow in 
            // \SymbolCache\src\source\.NET\4\DEVDIV_TFS\Dev10\Releases\RTMRel\ndp\clr\src\BCL\System\Threading\ExecutionContext.cs\1305376\ExecutionContext.cs
            // at line 435
            System.Diagnostics.Trace.CorrelationManager.StartLogicalOperation("LogicalOperation");

            var task = Task.Factory.StartNew(() => { });
            var cont = task.ContinueWith(MyContinueWith, CancellationToken.None, TaskContinuationOptions.None, ts);

            System.Diagnostics.Trace.CorrelationManager.StopLogicalOperation();
        }

        void MyContinueWith(Task t)
        {
            if (SynchronizationContext.Current == null) // The current SynchronizationContext shouldn't be null here, but it is.
                MessageBox.Show("SynchronizationContext.Current is null");
        }
    }
}

継続から使用しようとしているため、これは私にとっての問題でBackgroundWorkerあり、BackgroundWorkerはそのイベントRunWorkerCompletedとに現在のSynchronizationContextを使用しますProgressChanged。BackgroundWorkerを開始すると、現在のSynchronizationContextがnullになるため、意図したとおりにイベントがメインUIスレッドで実行されません。

私の質問:
これはMicrosoftのコードのバグですか、それともどこかで間違いを犯しましたか?

追加情報:

  • .Net 4.0を使用しています(.NET 4.5 RCではまだ試していません)
  • これは、任意のx86 / x64 /任意のCPU(x64マシン上)のデバッグ/リリースの両方で再現できます。
  • 一貫して再現します(誰かが再現できない場合は興味があります)。
  • 私はBackgroundWorkerを使用するレガシーコードを持っているので、BackgroundWorkerを使用しないように簡単に切り替えることはできません
  • のコードがMyContinueWithメインのUIスレッドで実行されていることを確認しました。
  • 呼び出しが問題の原因となる理由が正確にはわかりませんStartLogicalOperation。それが、アプリケーションで絞り込んだものです。
4

1 に答える 1

21

この問題は.NET4.5RCで修正されています(テストしたばかりです)。したがって、これは.NET4.0のバグだと思います。また、これらの投稿は同じ問題を参照していると思います:

それは残念です。ここで、回避策を検討する必要があります。

編集:
デバッグから.Netソースへの移行から、問題がいつ再現されるかについて少しよく理解しています。以下は、ExecutionContext.csの関連コードです。

        internal static void Run(ExecutionContext executionContext, ContextCallback callback,  Object state, bool ignoreSyncCtx) 
        {
            // ... Some code excluded here ...

            ExecutionContext ec = Thread.CurrentThread.GetExecutionContextNoCreate();
            if ( (ec == null || ec.IsDefaultFTContext(ignoreSyncCtx)) &&
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
                SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) && 
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
                executionContext.IsDefaultFTContext(ignoreSyncCtx)) 
            { 
                callback(state);
            } 
            else
            {
                if (executionContext == s_dummyDefaultEC)
                    executionContext = s_dummyDefaultEC.CreateCopy(); 
                RunInternal(executionContext, callback, state);
            } 
        } 

この問題は、RunInternalを呼び出す「else」句に入ったときにのみ再現されます。これは、RunInternalがExecutionContextを置き換えることになり、現在のSynchronizationContextを変更する効果があるためです。

        // Get the current SynchronizationContext on the current thread 
        public static SynchronizationContext Current 
        {
            get
            { 
                SynchronizationContext context = null;
                ExecutionContext ec = Thread.CurrentThread.GetExecutionContextNoCreate(); 
                if (ec != null) 
                {
                    context = ec.SynchronizationContext; 
                }

                // ... Some code excluded ...
                return context;
            }
        } 

したがって、私の特定のケースでは、行 `executionContext.IsDefaultFTContext(ignoreSyncCtx))がfalseを返したためです。そのコードは次のとおりです。

        internal bool IsDefaultFTContext(bool ignoreSyncCtx)
        { 
#if FEATURE_CAS_POLICY 
            if (_hostExecutionContext != null)
                return false; 
#endif // FEATURE_CAS_POLICY
#if FEATURE_SYNCHRONIZATIONCONTEXT
            if (!ignoreSyncCtx && _syncContext != null)
                return false; 
#endif // #if FEATURE_SYNCHRONIZATIONCONTEXT
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK 
            if (_securityContext != null && !_securityContext.IsDefaultFTSecurityContext()) 
                return false;
#endif //#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK 
            if (_logicalCallContext != null && _logicalCallContext.HasInfo)
                return false;
            if (_illogicalCallContext != null && _illogicalCallContext.HasUserData)
                return false; 
            return true;
        } 

_logicalCallContext.HasInfo私にとって、それは本当だったので偽を返していました。そのコードは次のとおりです。

public bool HasInfo
{ 
    [System.Security.SecurityCritical]  // auto-generated
    get
    {
        bool fInfo = false; 

        // Set the flag to true if there is either remoting data, or 
        // security data or user data 
        if(
            (m_RemotingData != null &&  m_RemotingData.HasInfo) || 
            (m_SecurityData != null &&  m_SecurityData.HasInfo) ||
            (m_HostContext != null) ||
            HasUserData
          ) 
        {
            fInfo = true; 
        } 

        return fInfo; 
    }
}

私にとって、HasUserDataがtrueだったので、これはtrueを返していました。そのコードは次のとおりです。

    internal bool HasUserData
    {
        get { return ((m_Datastore != null) && (m_Datastore.Count > 0));} 
    }

私の場合、m_DataStoreには、Diagnostics.Trace.CorrelationManager.StartLogicalOperation("LogicalOperation");

要約すると、バグを再現する方法はいくつかあるようです。うまくいけば、この例は、他の人がこの同じバグに遭遇しているかどうかを判断するのに役立つでしょう。

于 2012-07-24T15:45:03.120 に答える