基于标志Finesedequeue停止线程在下面的线程方法中我在停止按钮中做了一个循环(其目的是在填充名为_textFromFilesQueue的队列后停止此线程)并且主要问题在于我的形式冻结
这是我的代码:
线程方法:
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);
}
}
停止按钮单击:
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
如果有任何人可以帮助我,非常感谢你
答案 0 :(得分:-1)
忙碌时等待睡觉是个好主意,这样你就可以让其他线程有机会执行。
5
您还可以查看Task类
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx这对于诸如文件IO之类的异步操作很有用,并且可以使用内置的while (!Thread1.Finisedqueue)
{
Thread.Sleep(100);
Console.WriteLine("Queue from First Thread is still Enqueuing data");
}
功能来等待。
async/await