Reputation: 97
how to Abort, pause or resume a thread?
cause im having run time error with .Abort()
(Object reference was not set to an object instance.) and with .Resume()
and .Suspend()
there is a Obselete error.
I tryed in my Run()
a Thread.Sleep(1000) But i realize that it will not work because it's not the instance of the thread that was used.
Any idea how can i do it?
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;
}
Upvotes: 0
Views: 332
Reputation: 99
Do not use Thread, use Task instead. You can run new task:
Task.Run(()=>...);
You can use CancellationToken/CancellationTokenSource to achieve make your task cancelable:
If you want to pause your task you can try to implement something like this:
https://blogs.msdn.microsoft.com/pfxteam/2013/01/13/cooperatively-pausing-async-methods/
Upvotes: 1