Last active
May 3, 2016 09:33
-
-
Save Baekalfen/1daa55b21260f67a6d53443630c1851d to your computer and use it in GitHub Desktop.
C# .NET/Mono -- Quick template for using a ThreadPool
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
private struct Context | |
{ | |
public string val; | |
public ManualResetEvent doneEvent; | |
} | |
private void FunctionOnContext(object context){ | |
Context c = (Context)context; | |
lock (resultList) { | |
resultList.Add (new Result(c.val)); | |
} | |
c.doneEvent.Set (); | |
} | |
private void doThreadPool(List<T> things) | |
{ | |
ManualResetEvent[] doneEvents = new ManualResetEvent[things.Count]; | |
resultList = new List<Result> (); | |
int i = 0; | |
foreach (var thing in things) | |
{ | |
doneEvents[i] = new ManualResetEvent(false); | |
Context context = new Context { | |
val = thing, | |
doneEvent = doneEvents [i] | |
}; | |
ThreadPool.QueueUserWorkItem ( | |
new WaitCallback (FunctionOnContext), | |
context | |
); | |
i++; | |
} | |
WaitHandle.WaitAll (doneEvents); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment