i have (want) to execute a search request to multiple sources. Now i've done some multithreading in the past, but it was all fire and forget.
Now what i want to do, is to spin up 3 identical requests on 3 different objects, wait until they are all 'done' (and that gives me the first question: how do they say 'i'm done', and then collect all the data thet've sent me.
So in pseudo code i have this interface:
interface ISearch
SearchResult SearchForContent(SearchCriteria criteria)
So in code i create the three search services:
ISearch s1 = new SearchLocal();
ISearch s2 = new SearchThere();
ISearch s3 = new SearchHere();
And then call SearchForContent(SearchCriteria criteria)
on all three of them, in a multihreaded / async way
and the they all come back to me with their SearchResult
and after they are ALL done, i process their SearchResult
objects.
I hope these lines of text kindof makes you get what is in my head :)
i'm working on a ASP.Net 3.5 C# project.
Create AutoResetEvent
and pass them to WaitHandle.WaitAll()
There is an example here.
Basically:
1) You create an AutoResetEvent
for each search and pass false
to its constructor.
2) Create the threads and run search for each one and at the end, call Set
on the AutoResetEvent
in the finally block. It is very important that calling Set
is done inside the finally block otherwise WaitAll()
will be waiting indefinitely.
3) In the code right after you have spawned the threads, you call WaitHandle.WaitAll()
and pass all those AutoResetEvent
to it. This code will wait until all is finished.
Using tasks you could do a continuation like this:
Task[] t = new Task[2];
t[0] = Task.Factory.StartNew(() => { Thread.Sleep(1000); });
t[1] = Task.Factory.StartNew(() => { Thread.Sleep(2000); });
Task.Factory.ContinueWhenAll(t, myTasks => { Console.WriteLine("All done!"); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With