【问题标题】:Stop thread from working after it fills the queue填满队列后停止线程工作
【发布时间】:2016-10-31 14:57:34
【问题描述】:

停止基于标志 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 

如果有人可以帮助我,非常感谢您

【问题讨论】:

  • 您的表单在while 循环中冻结。
  • 我该如何解决这个问题!
  • 您的 StopClick 不会停止任何操作,它只是挂起,直到所有工作完成。
  • 您可能应该使用 BlockingCollection。还有 Tasks 和 CancelationTokens 和 EnumerateFiles 和 ...

标签: c# multithreading


【解决方案1】:

当忙于等待时,最好睡一觉,这样你就可以给其他线程一个执行的机会。

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

您还可以查看 Task 类 https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx 非常适合异步操作,例如文件 IO,并且可以使用内置的 async/await 功能等待。

private Queue<string> q = new Queue<string>();
private Task readFilesTask;
public void ReadFiles(string inputDirectory)
{
    var files = Directory.GetFiles(inputDirectory, "*.txt", SearchOption.TopDirectoryOnly);
    foreach (var file in files)
    {
        var textFromFile = File.ReadAllText(file);
        q.Enqueue(textFromFile);
        File.Delete(file);
    }
}

private void start_Click(object sender, EventArgs e)
{
    readFilesTask = Task.Run(() => ReadFiles("//path/to/dir"));
}

private void stop_Click(object sender, EventArgs e)
{    
    readFilesTask.Wait();
    //readFilesTask.Wait(1000); // if you want kill the task after waiting for 1000 milliseconds
    //Enable buttons
}

【讨论】:

  • 如果可以的话,您也可以使用 Thread.Yield 方法来获得更好的性能(这可能因您的 .NET 版本而异
  • 你能给我一个例子在我的情况下改变我的代码!谢谢
猜你喜欢
  • 2012-02-09
  • 1970-01-01
  • 2022-10-20
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
相关资源
最近更新 更多