none
Thread.Sleep是什么意思? RRS feed

  • 问题

  • //主窗口:

    public partial class Form1 : Form { private FormProgressbar _frmProgressBar; //instance of ProgressBar form. private delegate bool IncreaseProBarHandler(int val); //delegate to handler the corresponding. private IncreaseProBarHandler _incProBar; //instance of the handler. public Form1() { InitializeComponent(); } //Show the ProgressBar form. void ProgressBarFormShow() { _frmProgressBar = new FormProgressbar(); _incProBar = _frmProgressBar.IncreaseProbarVal; _frmProgressBar.ShowDialog(); //treat the ProgressBar as modal dialog. } //Management the ProgressBar form. void MngProgressBarForm() { try { MethodInvoker proBarFormInvo = ProgressBarFormShow; this.BeginInvoke(proBarFormInvo); Thread.Sleep(1000); //sleep for a while to show the window. bool bIncProBar = false; //determine whether increase the ProgressBar successfully. do { Thread.Sleep(5); //sleep a while each time trying to increase the ProgressBar value. bIncProBar = (bool)this.Invoke(_incProBar, new object[] { 2 }); } while(bIncProBar); } catch(System.Exception ex) { MessageBox.Show(ex.Message); } } //Store the selected directory. private void btn_OpenFD_Click(object sender, EventArgs e) { FolderBrowserDialog folderBD = new FolderBrowserDialog(); if(folderBD.ShowDialog() == DialogResult.OK) comBoxPath.Text = folderBD.SelectedPath; } //Start to read. private void btnRead_Click(object sender, EventArgs e) { new Thread(MngProgressBarForm).Start(); //start the ProgressBar Thread. ArrayList arrDirs = new ArrayList(); //存储路径列表. ArrayList arrFiles = new ArrayList(); //存储文件列表. GetFilesList(comBoxPath.Text.Trim(), "*.*", arrDirs, arrFiles, true); StringBuilder strBuilder = new StringBuilder(arrDirs.Count + arrFiles.Count); //拼接文件/文件名. foreach(var dir in arrDirs) { //路径. strBuilder.Append(dir + "\n"); } foreach(var file in arrFiles) { //文件. strBuilder.Append(file + "\n"); } richTxtShow.Text = Convert.ToString(strBuilder); labCountAll.Text = "总共找到\"" + arrDirs.Count + "\"文件夹, \"" + arrFiles.Count + "\" 文件."; } //Get File/Directory List. /// <summary> /// 读取指定路径下全部"路径/文件"并用列表存储. /// </summary> /// <param name="strDir">指定读取的路径.</param> /// <param name="strFilePattern">读取文件的格式.</param> /// <param name="arrDirs">存储路径的ArrayList.</param> /// <param name="arrFiles">存储文件的ArrayList.</param> /// <param name="bIsRecursive">是否递归读取.</param> private void GetFilesList(string strDir, string strFilePattern, System.Collections.ArrayList arrDirs, System.Collections.ArrayList arrFiles, bool bIsRecursive) { //None directory. if(string.IsNullOrEmpty(strDir)) throw new ArgumentNullException("Directory"); try { DirectoryInfo dir = new DirectoryInfo(strDir); string result = ""; //存储与查找文件/文件名相符的文件名/路径名. //Directory. //string[] directorys = Directory.GetDirectories(strDir); DirectoryInfo[] directorys = dir.GetDirectories(); foreach(var d in directorys) { result = d.Name.ToLower(); if(result.Contains(txtFileSearch.Text.ToLower().Trim())) arrDirs.Add(d.FullName); } //File. //string[] files = Directory.GetFiles(strDir, strFilePattern); FileInfo[] files = dir.GetFiles(); foreach(var f in files) { result = f.Name.ToLower(); if(result.Contains(txtFileSearch.Text.ToLower().Trim())) arrFiles.Add(f.FullName); } //Recursive. if(bIsRecursive) { foreach(var d in directorys) { GetFilesList(d.FullName + "\\" + d.Name, strFilePattern, arrDirs, arrFiles, true); } } } catch(System.Exception ex) { richTxtShow.Text = ex.Message; } } private void Form1_Load(object sender, EventArgs e) { comBoxPath.SelectedIndex = 0; //初始选项路径. } }

    //进度条窗口:
    public partial class FormProgressbar : Form {
            public FormProgressbar() {
                InitializeComponent();
            }
            /// <summary>
            /// increase the progressbar value.
            /// </summary>
            /// <param name="val">the val to increase each time.</param>
            /// <returns>true if it increase successfully;otherwise false.</returns>
            public bool IncreaseProbarVal(int val) {
                if(probar.Value + val < probar.Maximum) {
                    probar.Value += val;
                    return true;
                }
                else {
                    probar.Value = probar.Maximum;
                    return false;
                }
            }
        }

    //以上我的查找文件的时候,添加的一个进度条,查找文件没有问题...
    我发现的是,在这里的话,进度条处理的方法:
    //Management the ProgressBar form.
            void MngProgressBarForm() {
                try {
                    MethodInvoker proBarFormInvo = ProgressBarFormShow;
                    this.BeginInvoke(proBarFormInvo);
    
                    Thread.Sleep(1000);  //sleep for a while to show the window.
    
                    bool bIncProBar = false;    //determine whether increase the ProgressBar successfully.
                    do {
                        Thread.Sleep(5);   //sleep a while each time trying to increase the ProgressBar value.
                        bIncProBar = (bool)this.Invoke(_incProBar, new object[] { 2 });
                    } while(bIncProBar);
                }
                catch(System.Exception ex) {
                    MessageBox.Show(ex.Message);
                }
    
            }
    
    //中, Thread.Sleep(1000);  //sleep for a while to show the window.如果改成线程暂停时间较短的话,进度条窗口不前进...什么意思哈...


    2013年6月22日 15:00

答案

全部回复

  • Thread.Sleep(1000):把当前线程暂停1秒(延时一秒)。

    等到异步完成之后继续同步的方法。


    If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

    Help by clicking:
    Click here to donate your rice to the poor
    Click to Donate
    Click to feed Dogs & Cats


    Found any spamming-senders? Please report at: Spam Report

    2013年6月23日 1:19
    版主
  • 额...我不懂的是,

    MethodInvoker progressbarInvo = new MethodInvoker(ShowProgressbarForm);
                    this.BeginInvoke(progressbarInvo);

    然后 Thread.Sleep(100); //sleep a while to show the main form.

    所以,这两个有关,所以这里的Thread.Sleep是主线程?

    你说的意思我懂,但是不知道这里的"当前"线程....是哪个线程...

    是主窗口的线程,还是我new Thread(MngProgressBarForm).Start(); 是时候的进度条窗口?

    2013年6月23日 9:32
  • 没有关系,恐怕你误会我的意思了。

    Thread的Sleep方法在哪个方法中调用,该方法属于哪个线程,Sleep自然就屏蔽哪个线程。

    显然你MngProgressBarForm被一个Thread调用,明显Sleep屏蔽的是这个子线程。

    因为你在方法中使用了this.BeginInvoke,this显然是主窗体的UI线程,当然可以操作任意的UI上的窗体控件。

    我建议看看我写的这篇博文:使用委托的BeginInvoke方法来完成复杂任务的操作


    If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

    Help by clicking:
    Click here to donate your rice to the poor
    Click to Donate
    Click to feed Dogs & Cats


    Found any spamming-senders? Please report at: Spam Report

    2013年6月24日 1:29
    版主
  • "Thread的Sleep方法在哪个方法中调用,该方法属于哪个线程,Sleep自然就屏蔽哪个线程。"这个说的貌似是"后台线程(即用BeginInvoke"产生的异步线程>

    但是,貌似你博文说的,是主线程...我调试的时候,发现...Thread.Sleep中不是后台线程....那应该是主线程哦....

    2013年6月24日 15:24
  • 我记得你另外的帖子中貌似用一个新的Thread来调用MngProgressBarForm方法的,那肯定是子线程。

    如果你不用Thread去调用,那么为主线程。


    If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

    Help by clicking:
    Click here to donate your rice to the poor
    Click to Donate
    Click to feed Dogs & Cats


    Found any spamming-senders? Please report at: Spam Report

    2013年6月25日 1:10
    版主
  • 是同一个问题的....开始我疑问发帖不成功,所以重发了一次...所以我说你说的两次都不一样哈...但是,如果 Thread.Sleep的是子线程的话,貌似有点不通顺...

    因为

    this.BeginInvoke(proBarFormInvo); Thread.Sleep(1000); //sleep for a while to show the window.

    ....//总之你两次说的...搞得我现在更乱了...

    2013年6月25日 4:45
  • 我两次说的都一样啊……总而言之:Thread属于哪个线程取决于Thread的Sleep所在方法隶属哪一个线程。

    If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

    Help by clicking:
    Click here to donate your rice to the poor
    Click to Donate
    Click to feed Dogs & Cats


    Found any spamming-senders? Please report at: Spam Report

    2013年6月25日 5:46
    版主