Categories
askquestion

multithreading while blocking main thread

multithreading while blocking main thread

Ask Question

Asked
10 years, 6 months ago

Active
10 years, 6 months ago

Viewed
2k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

4

1

How do I start 2 or more threads all at once and block the main thread until the others threads are complete?

c# multithreading

share|improve this question

edited Sep 15 ’09 at 14:35

paxdiablo

704k194194 gold badges13761376 silver badges17601760 bronze badges

asked Sep 15 ’09 at 14:30

user125155user125155

4122 bronze badges

Threading in C# for the question above

– user125155
Sep 15 ’09 at 14:34

add a comment
 | 

4 Answers
4

Active

Oldest

Votes

12

From the main thread, call Thread.Join on each of the other threads.

(EDIT: Now you’ve specified C#, there’s no need for the platform agnostic comment.)

For example:

Thread t1 = new Thread(FirstMethod).Start();
Thread t2 = new Thread(SecondMethod).Start();

t1.Join();
t2.Join();

It doesn’t matter what order you call Join in, if you only want to wait until they’ve all finished. (If you want to continue when any of them have finished, you need to get into the realm of wait handles.)

share|improve this answer

edited Sep 15 ’09 at 14:49

answered Sep 15 ’09 at 14:31

Jon SkeetJon Skeet

1172k746746 gold badges83898389 silver badges87178717 bronze badges

In .NET 4.0 you may also get value out of using a System.Threading.CountdownEvent and calling ‘Signal’ on the child threads and ‘Wait’ on the main thread, or System.Threading.Barrier and call SignalAndWait on all three threads.

– Rick
Sep 16 ’09 at 6:11

add a comment
 | 

2

public delegate void AsyncTask(object state);

public void Method1(object state) …..

public void Method2(object state) …..

public void RunAsyncAndWait(){

AsyncTask ac1 = new AsyncTask(Method1);
AsyncTask ac2 = new AsyncTask(Method2);

WaitHandle[] waits = new WaitHandle[2];

IAsyncResult r1 = ac1.BeginInvoke( someData , null , null );
IAsyncResult r2 = ac2.BeginInvoke( someData , null , null );

waits[0] = r1.AsyncWaitHandle;
waits[1] = r2.AsyncWaitHandle;

WaitHandle.WaitAll(waits);

}

This works, some people will aruge that if any of thread finishes first it will wait endlessly but I have tried, it have worked always. You can also give timeout to wait for. And in BeginInvoke first parameter is the value passed inside your methods.

share|improve this answer

answered Sep 15 ’09 at 14:55

Akash KavaAkash Kava

35.7k2020 gold badges109109 silver badges157157 bronze badges

add a comment
 | 

0

There’s a good example of how to do threading in C# on MSDN

http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx#vcwlkthreadingtutorialexample1creating

If you look at the Mutex example it demonstrates putting the main thread to sleep until all child threads have completed.

share|improve this answer

answered Sep 15 ’09 at 14:42

GwareddGwaredd

1,54711 gold badge1010 silver badges1212 bronze badges

or Mutex example even 😉

– Gwaredd
Sep 15 ’09 at 14:43

add a comment
 | 

0

Jeffry Richter of Wintellect has a library for download called the Power Threading library. I have not used it myself but it might be helpful.

share|improve this answer

answered Sep 15 ’09 at 15:02

HitLikeAHammerHitLikeAHammer

2,45922 gold badges3333 silver badges5151 bronze badges

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Submit

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged c# multithreading or ask your own question.

The Overflow Blog

Podcast Episode 220: Fully Remote

Tracking down performance pitfalls in Vue.js

Featured on Meta

Planned maintenance scheduled for Saturday, March 28, 2020 at 13:00 UTC (9AM…

An Update On Creative Commons Licensing

Community and Moderator guidelines for escalating issues via new response…

How does the Triage queue work?

Triage needs to be fixed urgently, and users need to be notified upon…

Related

574Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on1601What is the difference between a process and a thread?2087“implements Runnable” vs “extends Thread” in Java1371How do I update the GUI from another thread?1536How do I remedy the “The breakpoint will not currently be hit. No symbols have been loaded for this document.” warning?1252How can I use threading in Python?1128How do servlets work? Instantiation, sessions, shared variables and multithreading1863C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?314Running code in main thread from another thread380How to check if current thread is not main thread

Hot Network Questions

How much of the US media referred to the COVID-19 as the “Wuhan Virus” until it received an official designation from the WHO?

How can my vampires hide in public?

AuraEnabled Method Causes Internal Server Error for non-Admin Profile

Drawing 2.0A from 9v Battery for 5 Seconds

Cat Keeps Drinking Unattended Drinks

How do “tip jet” helicopters cancel the torque effect of the main rotor?

Has radio astronomy ever been done on objects that appear very close to the Moon? Is this avoided?

Could Byzantines Bridge a Deep Strait Separating 2 Continents?

Update error (Err:7 http://raspbian.raspberrypi.org/raspbian stretch/main armhf Packages)

Why is the effect called Dodge?

Did Russia release lions onto the streets to keep people in isolation?

Why is it funny to say Giri played the Evans Gambit?

My professor is not teaching his online course himself, but uses publicly available videos instead. Is this appropriate?

A suit that realistically protects against impact, falling, being thrown around?

Do Kohanim fast on Yom Kippur in the Bet Hamikdash?

circuit analysis transient response in an RC circuit

Safe to mount rear rack for Grail 7.0 al 2020 ( no eyelets )?

What should I call a “differential” which cubes, rather than squares, to zero?

Any Implementation in C++

Why should one pre-heat an oven?

Are Putin’s constitution amendments legal?

Identify a book where the main character is released from prison in order to be sent to conduct espionage in Italy

How much project management is a software developer supposed to do?

When filing taxes, how do I report “informal income” for which I don’t have any forms?

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-cs

Leave a Reply

Your email address will not be published. Required fields are marked *