Void’s Vault

Knowledge source for efficiency.

Parallelism in .NET - Using Task Factory

Special Thanks to ReedCopsey, Jr. I found that on his website, and it was very helpful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Start our task on a background thread
var task = Task.Factory.StartNew(() => this.ExecuteBackgroundWork(myData) );
// Do other work on the main thread, 
// while the task above executes in the background
this.ExecuteWorkSynchronously();
// Wait for the background task to finish
task.Wait();

// Construct a task scheduler from the current SynchronizationContext (UI thread)
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
// Construct a new TaskFactory using our UI scheduler
var uiTaskFactory = new TaskFactory(uiScheduler);

// When inside a background task, we can do
string status = GetUpdatedStatus();
// Update our UI
uiTaskFactory.StartNew( () => statusLabel.Text = status);