首页 > 解决方案 > 如何暂停线程?

问题描述

相关代码:

private static Thread m_thread = null;
private static Boolean m_stop = false;

public static Boolean Start(SearcherParams pars)
{
    Boolean success = false;

    if (m_thread == null)
    {
        // Perform a reset of all variables,
        // to ensure that the state of the searcher is the same on every new start:
        ResetVariables();

        // Remember the parameters:
        m_pars = pars;

        // Start searching for FileSystemInfos that match the parameters:
        m_thread = new Thread(new ThreadStart(SearchThread));
        m_thread.Start();

        success = true;
    }

    return success;
}

private static void SearchThread()
{
    Boolean success = true;
    String errorMsg = "";

    // Search for FileSystemInfos that match the parameters:
    if ((m_pars.SearchDir.Length >= 3) && (Directory.Exists(m_pars.SearchDir)))
    {
        if (m_pars.FileNames.Count > 0)
        {
            // Convert the string to search for into bytes if necessary:
            if (m_pars.ContainingChecked)
            {
                if (m_pars.ContainingText != "")
                {
                    try
                    {
                        m_containingBytes = 
                            m_pars.Encoding.GetBytes(m_pars.ContainingText);
                    }
                    catch (Exception)
                    {
                        success = false;
                        errorMsg = "The string\r\n" + m_pars.ContainingText +
                                    "\r\ncannot be converted into bytes.";
                    }
                }
                else
                {
                    success = false;
                    errorMsg = "The string to search for must not be empty.";
                }
            }

            if (success)
            {
                // Get the directory info for the search directory:
                DirectoryInfo dirInfo = null;

                try
                {
                    dirInfo = new DirectoryInfo(m_pars.SearchDir);
                }
                catch (Exception ex)
                {
                    success = false;
                    errorMsg = ex.Message;
                }

                if (success)
                {
                    // Search the directory (maybe recursively),
                    // and raise events if something was found:
                    SearchDirectory(dirInfo);
                }
            }
        }
        else
        {
            success = false;
            errorMsg = "Please enter one or more filenames to search for.";
        }
    }
    else
    {
        success = false;
        errorMsg = "The directory\r\n" + m_pars.SearchDir + "\r\ndoes not exist.";
    }

    // Remember the thread has ended:
    m_thread = null;

    // Raise an event:
    if (ThreadEnded != null)
    {
        ThreadEnded(new ThreadEndedEventArgs(success, errorMsg));
    }
}

private static void SearchDirectory(DirectoryInfo dirInfo)
{
    if (!m_stop)
    {
        try
        {
            foreach (String fileName in m_pars.FileNames)
            {
                FileSystemInfo[] infos = dirInfo.GetFileSystemInfos(fileName);

                foreach (FileSystemInfo info in infos)
                {
                    if (m_stop)
                    {
                        break;
                    }

                    if (MatchesRestrictions(info))
                    {
                        // We have found a matching FileSystemInfo, 
                        // so let's raise an event:
                        if (FoundInfo != null)
                        {
                            FoundInfo(new FoundInfoEventArgs(info));
                        }
                    }
                }
            }

            if (m_pars.IncludeSubDirsChecked)
            {
                DirectoryInfo[] subDirInfos = dirInfo.GetDirectories();

                foreach (DirectoryInfo subDirInfo in subDirInfos)
                {
                    if (m_stop)
                    {
                        break;
                    }

                    // Recursion:
                    SearchDirectory(subDirInfo);
                }
            }
        }
        catch (Exception)
        {
        }
    }
}          

停止工作正常我还想添加一个暂停按钮来暂停和恢复线程。我添加了一个按钮单击事件,但是如何进行暂停/恢复操作以及在哪里?

这是完整代码的链接:https ://pastebin.com/fYYnHBB6

标签: c#winforms

解决方案


您可以使用ManualResetEvent对象。

这里是简化版。

  1. 在您的班级中,创建对象:

    public static ManualResetEvent _mrsevent = new ManualResetEvent(false);
    
  2. 在您的线程函数中,作为搜索文件/目录的循环的一部分:

    private static void SearchThread()
    {
       foreach (String fileName in m_pars.FileNames)
       {
          _mrsevent.WaitOne();
       }
    }
    
  3. 您可以从线程外部调用:

    一)_mrsevent.Set();// 恢复线程。

    b) _mrsevent.Reset(); // 暂停


推荐阅读