Main Site Documentation

Threading questions


#1

Guys,

i was wondering if there is a difference in doing:

(pseudo code but you get the point)

  1. start the thread in program.cs main function

public static void Main()
  {
    thread classthread = new thread(myclass);
    classthread.start();
  }

class myclass
  {
     void myclass()
     {
       startmyclass();
     }

     void startmyclass()
     {
       //do something
     }
  }   

and

  1. start the thread in the class

public static void Main()
  {
    myclass();
  }

class myclass
  {
     void myclass()
     {
       thread myclass = new thread(startmyclass);
       myclass.start();
     }

     void startmyclass()
     {
       //do something
     }
  }   


#2

From what I understand, you’re first pseudo code is using a class constructor as Thread delegate. To be honest, I never tried that and I never will.

The best approach is to start the thread from within the class as in your second pseudo code. Since the thread is (in most cases) part of the class functionality.


#3

In my code I always try to make constructor as light weight as possible and move any heavy initialization into a separate method.


#4

2nd. You want the class to “contain” its functionality. Typically, I would use a Start() method on the class.