2017-09-06 86 views
0

如何中止,暫停或恢復線程?C#多線程.abort().suspend().reusme()

原因IM已經與運行時錯誤。 Abort()(對象引用未設置爲對象實例),並且.Resume().Suspend()存在Obselete錯誤。

我tryed我Run()一個Thread.sleep代碼(1000),但我意識到,它不會工作,因爲它不是已使用的線程的實例。

任何想法,我該怎麼辦呢?

THX

CODE:

class FolderStats : IFolderStats 
{ 
    Thread MyThread = null; 
    private bool x; 
    string Rootpath; 
    List<string> MyList = new List<string>(); 
    Folder FD = new Folder(); 

    public void Connect(string rootpath) 
    { 

     Console.WriteLine(Statuses.Waiting); 
     Thread.Sleep(1000); 

     FD.Path = rootpath; 
     Rootpath = rootpath; 

     Console.WriteLine(Statuses.Connected); 
     Thread.Sleep(1000); 
    } 

    public void Start() 
    { 
     MyThread = new Thread(Run); 
     MyThread.Start(); 
     Console.WriteLine("Starting the Search"); 
    }   
    public void Stop() 
    { 
     MyThread.Abort(); 
     Console.WriteLine("Console Aborted. Please press Enter to Exit"); 
    } 
    public void Pause() 
    { 
     this.x = false; 
     PauseResume(); 
     Console.WriteLine("Console Paused."); 
    } 
    public void Resume() 
    { 
     this.x = true; 
     PauseResume(); 
     Console.WriteLine("Console Resumed."); 
    } 
    private void PauseResume() 
    { 
     while (this.x == false) 
     { 
      Thread.Sleep(100); 
     } 
    } 
    public void Run() 
    { 

     MyThread = new Thread(Start); 
     if (!MyList.Contains(Rootpath)) 
     { 
      MyList.Add(Rootpath); 
      var subDirs = Directory.GetDirectories(Rootpath, "*"); 
      var Data = Directory.GetFiles(Rootpath, "*"); 

      foreach (string dir in subDirs) 
      { 
       Thread.Sleep(2000); 
       Rootpath = dir; 
       Console.WriteLine(dir); 

       Run(); 
      } 
      foreach (string file in Data) 
      { 
       Thread.Sleep(2000); 
       if (!MyList.Contains(file)) 
       { 
        MyList.Add(file); 
        Console.WriteLine(file); 
       } 
      } 
     } 
     FD.NumberOfFiles = MyList.Count; 
    } 
+2

不要中止,暫停或恢復線程。你想要解決什麼是特定的任務? – Dennis

+0

數據收集應在調用Start()後在後臺完成。它可以隨時停止或暫停並恢復。 – k9nneo1191

+3

又見http://www.albahari.com/threading/ – rene

回答

1

不要使用線程,使用任務來代替。 您可以運行新的任務:

Task.Run(()=>...); 

可以使用的CancellationToken/CancellationTokenSource達到讓你的任務取消:

https://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

如果要暫停你的任務,你可以嘗試實施類似這:

https://blogs.msdn.microsoft.com/pfxteam/2013/01/13/cooperatively-pausing-async-methods/

+1

建議一個完全不同的概念並沒有真正讓OP瞭解爲什麼他不應該使用這些確切的方法(暫停,恢復,中止)以及他可以做什麼(使用相同的「線程概念」)。所以,雖然TAP應該是最好的選擇,但我不能贊成這個答案。 (但不會倒下) – Fildor