如何中止、暂停或恢复线程?
由于im使用.Abort()(对象引用未设置为对象实例)出现运行时错误。而对于.Resume()和.Suspend(),则存在一个错误。
我在我的Run()中尝试了一个Thread.Sleep(1000),但我意识到它不会工作,因为它不是所使用的线程的实例。
你知道我该怎么做吗?
thx
代码:
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;
}发布于 2017-09-06 20:28:55
不要使用Thread,而要使用Task。您可以运行新任务:
Task.Run(()=>...);您可以使用CancellationToken/CancellationTokenSource来实现使您的任务可取消:
如果你想暂停你的任务,你可以尝试实现类似这样的东西:
https://blogs.msdn.microsoft.com/pfxteam/2013/01/13/cooperatively-pausing-async-methods/
https://stackoverflow.com/questions/46074998
复制相似问题