开发者

Multithreaded/async request and wait till they are all done and then process the results

开发者 https://www.devze.com 2023-01-29 07:38 出处:网络
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.

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!"); });


Make an IEnumerable<ISearch>, and those items to it, and do .AsParallel().ForAll(...) on it.

Edit

ForAll won't return results, if you can change ISearch, give it a property for the results, then once the ForAll is done you can look at the results through the IEnumerable.

And yes, sorry, this is 4.0.

0

精彩评论

暂无评论...
验证码 换一张
取 消