I have a model that is data bound to controls in a view. One of the bound properties (of type BindingList<T>
) gets updated from another thread.
With help from this answer, I solved the "Cross-thread operation not valid" issue as follows (.NET 4.0, TPL):
public class Model : INotifyPropertyChanged
{
private readonly TaskFactory _uiThreadTaskFactory =
new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
private readonly object _myPropertyLocker = new object();
private void Handler()
{
// In another thread
_uiThreadTaskFactory.StartNew(
() =>
{
lock (_myPropertyLocker)
{
MyProperty.Add(someStuff);
}
});
}
}
This worked - until I tried to run my unit tests in ReSharper's test runner (v5.1). They threw the error
The current SynchronizationContext may not be used as a TaskScheduler.
on line
new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
How can I resolve this as elegantly as possible?