The Current Synchronizationcontext May Not Be Used as a Taskscheduler

The current SynchronizationContext may not be used as a TaskScheduler

You need to provide a SynchronizationContext. This is how I handle it:

[SetUp]
public void TestSetUp()
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
}

Top Level Task Causes Error The current SynchronizationContext may not be used as a TaskScheduler.

The cause is simple however the solution may require you to redesign some of the interactions of your tasks. You do not have a SynchronizationContext set (i.e. SynchronizationContext.Current is null), and therefore a TaskScheduler cannot be created from the it. One option is to call TaskScheduler.FromCurrentSynchronizationContext() in a place where you are running on the UI thread and then pass in down to the method where the continuations are constructed. Another is create the tasks an pass them up so that the UI thread can attach the continuations.

It is generally considered a code smell to have flags like _testMode that, presumably, only test code sets. Then you've got some interaction which you are not really testing because the test code does one thing, but the actual application does another.

Start thread returns System.InvalidOperationException: The current SynchronizationContext may not be used as a TaskScheduler

Without full context of the problem I can't give you an exact solution, but overall, you cannot access UI elements from another thread. That means you need to do all request and computation on another thread, and then update UI elements on UI thread. Consider such simplified solution that does not explicitly start a new thread:

// event on UI thread    
private async void frmMaterialDashboard_Load(object sender, EventArgs e)
{
var dashboardData = await LoadDashboardDataFromDatabaseAsync();
dashboardViewer1.Load(dashboardData);
}

public async Task<DashboardData> LoadDashboardDataFromDatabaseAsync()
{
string query = "...";
var queryResult = await db.ExucuteQueryAsync(query).ConfigureAwait(false);
return ConvertQueryRequltToDashboardData(queryResult);
}

TaskScheduler.FromCurrentSynchronizationContext() in .NET

put the creation of m_syncContextTaskScheduler into your form constructor .

public MyForm() {
Text = "Synchronization Context Task Scheduler Demo";
Visible = true; Width = 400; Height = 100;
m_syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
}


Related Topics



Leave a reply



Submit