私は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
。それが、アプリケーションで絞り込んだものです。