如何中止,暂停或恢复线程?
导致我的运行时错误。Abort()
(对象引用未设置为对象实例。)并且.Resume()
和.Suspend()
存在Obselete错误。
我尝试了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;
}
答案 0 :(得分:1)
不要使用Thread,而是使用Task。 您可以运行新任务:
Task.Run(()=>...);
您可以使用CancellationToken / CancellationTokenSource来实现让您的任务取消:
如果你想暂停你的任务,你可以尝试实现这样的事情:
https://blogs.msdn.microsoft.com/pfxteam/2013/01/13/cooperatively-pausing-async-methods/