Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a worker thread not execute when debugging the main thread?

I have created a console test application which creates, an object & calls 2 functions on 2 separate threads. One thread prints numbers form 1- 20 the other in the reverse order.

The problem is while debugging the 1st worker thread does not get fired till I don't stop debugging the main thread (i.e. I press f5). Any answers?

class Program
 {
  static void Main(string[] args)
   {
     DisplayData dd = new DisplayData();

     ThreadStart ts1 = new ThreadStart(dd.DisplayNumber);
     Thread t1 = new Thread(ts1);
     t1.Name = "Display Numbers";

     ThreadStart ts2 = new ThreadStart(dd.ReverseNumbers);
     Thread t2 = new Thread(ts2);
     t2.Name = "Reverse Numbers";

     t1.Start(); //Keep 1st break point at this location. Then press F10.
     t2.Start(); //Keep break point at this location permanently
    }




public class DisplayData
   {
       public void DisplayNumber()
       {
          int length = 20;
          Console.WriteLine("\nNumbers in correct order.\n");


          for (int i = 0; i < length; i++)
          {

             Console.WriteLine("DN: The value of i is: " + (i+1) + " " + Thread.CurrentThread.ManagedThreadId + " " + Thread.CurrentThread.Name);
             //Thread.Sleep(1000);

          }
       }

       public void ReverseNumbers()
       {
          int length = 20;
          Console.WriteLine("\nNumbers in reverse order.\n");
          for (int i = 0; i < length; i++)
          {

             Console.WriteLine("RN: The value of i is: " + (length - i) + " " + Thread.CurrentThread.ManagedThreadId + " " + Thread.CurrentThread.Name);
             //Thread.Sleep(1000);
          }
       }
like image 485
Ganesh R. Avatar asked Dec 28 '25 22:12

Ganesh R.


1 Answers

I'm not sure if this is a limitation in Visual Studio or the CLR but setting breakpoint on one thread will stop all threads.

If you want to pause a thread you can do this through the Debug..Threads window, you can pause and resume threads there.

like image 179
Kevin Jones Avatar answered Dec 31 '25 16:12

Kevin Jones



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!