A.H A.H - 1 month ago 17
C# Question

C# multiThreading Stop thread from working after it Fills the Queue

To stop The thread based on a flag Finesedequeue In the below thread method I did a loop in the stop button(its purpose is to stop this thread after it fills the queue named _textFromFilesQueue ) and the main problem in this is that my form is freezing

Here is my code:


The Threads Method :


public static bool Finisedqueue ;
public void Read(string inputDirectoryPath)
{

try
{
Thread.CurrentThread.IsBackground = true;
Finisedqueue = false;
Console.WriteLine("thread 1 started");
if (Form1.IsStarted)
{
Thread.Sleep(3000);
var dir = new DirectoryInfo(inputDirectoryPath);
FileInfo[] f = dir.GetFiles("*.txt");
if (f.Length > 0)
{
Console.WriteLine("{0} directory contains {1} Files",inputDirectoryPath,f.Length);
int counter = 0;
foreach (System.IO.FileInfo fi in f)
{

counter++;
var filePath = Path.Combine(fi.DirectoryName, fi.Name);
string textFromFile = File.ReadAllText(filePath);
_textFromFilesQueue.Enqueue(textFromFile);
Console.WriteLine("The text inside file number {0} is : {1}",counter,textFromFile);
fi.Delete();
Console.WriteLine("deleting file number {0} from input folder",counter);


}
Finisedqueue = true;
Console.WriteLine("finished Deleting files");
}

else
{
Console.WriteLine("{0} Has no files inside it ",inputDirectoryPath);
}
}

}
catch (Exception excep)
{
Console.WriteLine("An error occurred: '{0}'", excep);
throw(excep);

}
}



The Stop Button Click


private void stop_Click(object sender, EventArgs e)
{

while (!Thread1.Finisedqueue)
{
Console.WriteLine("Queue from First Thread is still Enqueuing data");
}
Thread1Timer.Dispose();
button3.Enabled = true;
textBox3.Enabled = true;



}
> the main problem in this is that my form is freezing


IF any body can help me in this Thank you very much

Answer

When busy waiting it is a good idea to sleep, so that you give other threads a chance to execute.

while (!Thread1.Finisedqueue)
{
    Thread.Sleep(100);
    Console.WriteLine("Queue from First Thread is still Enqueuing data");
}

You can also check out the Task class https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx which is nice for asynchronous operations such as file IO and is awaitable using the built-in async/await functionality.