Detecting a Thread is already running in C# .net?

前端 未结 5 1839
自闭症患者
自闭症患者 2020-12-15 14:29

I am using following code.

public void runThread(){
    if (System.Diagnostics.Process.GetProcessesByName(\"myThread\").Length == 0)
    {
    Thread t = new         


        
5条回答
  •  时光取名叫无心
    2020-12-15 14:56

    One easy way is that you could have a flag that indicates if it's running or not. You maybe have to use some lock if it's some conflicts.

    public static bool isThreadRunning = false;
    
    public void runThread()
    {
        if (!isThreadRunning)
        {
            Thread t = new Thread(new ThreadStart(go));
            t.IsBackground = true;
            t.Name = "myThread";
            t.Start();
        }
        else
        {
          System.Diagnostics.Debug.WriteLine("myThreadis already Running.");
        }   
    }
    public void go()
    {
        isThreadRunning = true;
        //My work goes here
        isThreadRunning = false;
    }
    

提交回复
热议问题