-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathThreadingHelper.cs
More file actions
40 lines (36 loc) · 1.35 KB
/
Copy pathThreadingHelper.cs
File metadata and controls
40 lines (36 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
namespace SyncPro.UI
{
using System;
using System.Threading;
using System.Threading.Tasks;
public static class ThreadingHelper
{
public static void StartBackgroundTask(Action<TaskScheduler, CancellationToken> backgroundAction)
{
StartBackgroundTask(backgroundAction, null);
}
public static void StartBackgroundTask(Action<TaskScheduler, CancellationToken> backgroundAction, Action<bool> completeAction)
{
var tokenSource = new CancellationTokenSource();
CancellationToken ct = tokenSource.Token;
TaskScheduler uiSyncContext = TaskScheduler.FromCurrentSynchronizationContext();
Task backgroundTask = Task.Factory.StartNew(() => backgroundAction(uiSyncContext, ct), ct);
if (completeAction != null)
{
backgroundTask.ContinueWith(delegate { completeAction(ct.IsCancellationRequested); }, uiSyncContext);
}
else
{
backgroundTask.ContinueWith(
task =>
{
if (task.Exception != null)
{
throw new Exception("Unhandled exception!", task.Exception);
}
},
ct);
}
}
}
}