Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pausing a Thread

I am using following code to create and execute thread i need to stop it but cant see thread .Sleep

any ideas how can i stop for a while the execution there?

var t = new Thread(() =>
{
try
   {
           //Line 1
             Pause here
           //Line 2
             Pause here
           //Line 3
   }
   catch (Exception ca)
   {
          MessageBox.Show(ca.Message);
   }
   });
   t.SetApartmentState(ApartmentState.STA);
   t.Start();
like image 424
Afnan Bashir Avatar asked Jul 13 '26 05:07

Afnan Bashir


2 Answers

If you mean that you want to instruct the Thread to wait at a particular checkpoint until some other Thread tells it to continue, one good option is to use AutoResetEvent.

like image 72
Dan Bryant Avatar answered Jul 14 '26 17:07

Dan Bryant


  t.SetApartmentState(ApartmentState.STA);

I'll work from the assumption that this was intentional. Couple of things you have to do to meet the STA contract. You have to pump a message loop, call Application.Run(). And you cannot pause, that blocks any marshaled call and makes deadlock very likely.

Not a problem, when you pump a message loop you're always in an idle 'pause' state. Make code run just as you'd normally do in a GUI main thread. Application.ExitThread ends the thread.

like image 24
Hans Passant Avatar answered Jul 14 '26 17:07

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!