に継続してnullである:
SynchronizationContext.Current
は、タスクの継続でヌルである(すなわち.ContinueWith
)上で実行されていますメインスレッド(私は現在の同期コンテキストがSystem.Windows.Forms.WindowsFormsSynchronizationContext
であることを期待しています)。ここでSynchronizationContext.Currentは、私はWinformsのアプリケーションで次の問題を追跡しようとしてきたメインUIスレッド
は、問題を実証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
とProgressChanged
の現在のSynchronizationContextを使用します。 BackgroundWorkerを起動すると、現在のSynchronizationContextがnullなので、イベントは主UIスレッドで実行されません。
私の質問:
が、これはMicrosoftのコードのバグですか、私はどこかでミスを犯してきましたか?
追加情報:
- 私は.NET 4.0を使用していますが、私はどんなの両方のデバッグ/リリースでこれを再現することができ
- (私はまだ.NET 4.5 RCでこれを試していません) x86/x64 /任意のCPU(x64マシン上)
- これは一貫して再現します(誰かがそれを再現できない場合は興味があります)。
- 私は、BackgroundWorkerのを使用してレガシーコードを持っている - ので、私は簡単に私が
MyContinueWith
のコードは、メインUIスレッド上で実行されていることを確認しましたBackgroundWorkerの - を使用していないに切り替えることはできません。
StartLogicalOperation
コールが問題の原因となっている理由を正確にはわかりませんが、それは私のアプリケーションで絞り込んだものです。
さて、あなたはそのリンクから診断を受けています。このWinformsアプリケーションにWPFまたはWCFコードを混在させていますか? –
いいえ - Winformsのみ。 –