1

I've the following Windows service code which starts a new thread to execute a long-running task. The task is stopped when I stop the Windows service.

public partial class WorkerService : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        Thread thread;
        thread = new Thread(DoWork);
        thread.IsBackground = true;
        thread.Start();
    }

    //OnStop code here

    private static void DoWork()
    {
        //Long-running task code here
    }
}

Does it matter if the DoWork method is static or not? Most of the sample code I find on the Web uses static. However, the code seems to be working fine without static.

    private void DoWork()
    {
        //Long-running task code here
    }

Is there anything I should be aware of when not using static for my DoWork method?

thd
  • 2,023
  • 7
  • 31
  • 45

1 Answers1

1

Here is a link to a similar SO question about static methods being thread safe. I always instantiate classes when working with threads and thread pools. One constructor, one use, one purpose. A thread is a special purpose mechanism and I see no reason why it should be shared or static or any gains by making your DoWork() a static method.

Community
  • 1
  • 1
Ross Bush
  • 14,648
  • 2
  • 32
  • 55