Skip to content

Instantly share code, notes, and snippets.

@Baekalfen
Last active May 3, 2016 09:33
Show Gist options
  • Save Baekalfen/1daa55b21260f67a6d53443630c1851d to your computer and use it in GitHub Desktop.
Save Baekalfen/1daa55b21260f67a6d53443630c1851d to your computer and use it in GitHub Desktop.
C# .NET/Mono -- Quick template for using a ThreadPool
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