Created
July 27, 2020 21:12
-
-
Save miroslavpopovic/15cde6444884795c3383b08186e5ef2d to your computer and use it in GitHub Desktop.
Dotnetos Async Expert: Module 02 homework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
namespace ThreadPoolExercises.Core | |
{ | |
public class ThreadingHelpers | |
{ | |
public static void ExecuteOnThread(Action action, int repeats, CancellationToken token = default, Action<Exception>? errorAction = null) | |
{ | |
// * Create a thread and execute there `action` given number of `repeats` - waiting for the execution! | |
// HINT: you may use `Join` to wait until created Thread finishes | |
// * In a loop, check whether `token` is not cancelled | |
// * If an `action` throws and exception (or token has been cancelled) - `errorAction` should be invoked (if provided) | |
var thread = new Thread(() => | |
{ | |
DoWork(action, repeats, token, errorAction); | |
}); | |
thread.Start(); | |
thread.Join(); | |
} | |
public static void ExecuteOnThreadPool(Action action, int repeats, CancellationToken token = default, Action<Exception>? errorAction = null) | |
{ | |
// * Queue work item to a thread pool that executes `action` given number of `repeats` - waiting for the execution! | |
// HINT: you may use `AutoResetEvent` to wait until the queued work item finishes | |
// * In a loop, check whether `token` is not cancelled | |
// * If an `action` throws and exception (or token has been cancelled) - `errorAction` should be invoked (if provided) | |
var ev = new AutoResetEvent(false); | |
ThreadPool.QueueUserWorkItem(state => | |
{ | |
DoWork(action, repeats, token, errorAction); | |
ev.Set(); | |
}); | |
ev.WaitOne(); | |
ev.Close(); | |
} | |
private static void DoWork(Action action, int repeats, CancellationToken token, Action<Exception>? errorAction = null) | |
{ | |
for (var i = 0; i < repeats; i++) | |
{ | |
try | |
{ | |
token.ThrowIfCancellationRequested(); | |
action(); | |
} | |
catch (Exception ex) | |
{ | |
errorAction?.Invoke(ex); | |
break; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment