简体   繁体   中英

How do I design threading for this program in C#?

I'm creating a program that will do a user-predefined number of tasks, say, 100.

Each task will go out to a server, fetch a response, make a call to another server, then use the response to make yet another call to the previous server.

I want the application to be multithreaded, so when the user presses a button it will launch, say, 10 threads and they will get going.

Once a task is complete, the thread which completed the task will grab another one from the list until there are none left in which case the threads will terminate and something will happen to alert the user the tasks were completed.

Previously when I attempted something similar I ended up with a cop-out where I basically launched 10 threads every N seconds or so and prayed the previous ones were over by then.

My question is, how do I make a number of threads, store them somehow and add tasks to them as they get completed? I was advised I could add thread references to a list and then check which threads where asleep and force them to do something but I'm not really sure how to do that, though mostly I'm not sure of the overall proper way to approach this problem.

Thanks!

First, make sure you really understand threading in .net. I found this is be a very good resource Threading in C# .

Also, new to the table, is Data Parallelism in .net 4. You can read more about this here

The data parallelism will make your situation easy (Parallel.ForEach), but I truly suggest you hit the books and learn the basics. But, if ignorance is bliss, then MS and Data Parallelism is for you.

If you don't have access to .net 4 and therefore Data Parallelism, then I you'll need a queue of tasks ( Queue(Of T) Class ), some lock for your threads to access it securely ( Locking ), background threads ( ThreadPool Class ), and some form of signalling ( Signaling with Wait and Pulse ).

Bonus. To limit/control threads working at a given time, you may also want to check out Semaphore .

Hope this helps.

It sounds like what you're asking for is the Task Parallel Library . Essentially, is helps to run tasks concurrently, without having to manage threads yourself. Although, you still have to understand the basics of multithreaded code so you can structure your program in way that supports running tasks in parallel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM