dimanche 1 mars 2015

SynchronizationContext is null in winforms

I'm creating a library which relies on capturing the SynchronizationContext in order to post callbacks back to the UI thread.


A user was having a weird condition where the callbacks were being posted to the ThreadPool instead. After investigating a bit, I came up with the following two test cases:


1:



public partial class Form1 : Form
{
private Test test;

public Form1()
{
test = new Test();
InitializeComponent();
}

private class Test
{
public Test()
{
if (SynchronizationContext.Current == null)
throw new InvalidOperationException("It's null! :(");
}
}
}


2:



public partial class Form1 : Form
{
private Test test = new Test();

public Form1()
{
InitializeComponent();
}

private class Test
{
public Test()
{
if (SynchronizationContext.Current == null)
throw new InvalidOperationException("It's null! :(");
}
}
}


The 1st test runs fine, but the 2nd one throws an exception. Why?


Aucun commentaire:

Enregistrer un commentaire