【问题标题】:Use Progressbar in a separate thread in order to run simultaneously in two different tasks在单独的线程中使用 Progressbar 以便在两个不同的任务中同时运行
【发布时间】:2012-09-20 08:50:39
【问题描述】:

我想同时运行两个函数。

第一个函数将统计我计算机中的文件总数,并将结果显示在一个 DatagridView 中。

并且在第二个函数中,会根据文件总数改变一个进度条的值,也就是说当DatagridView中绑定所有文件时,进度条的值将设置为100。

我想同步两个函数的工作,我在使用两个线程但是结果没有显示,发生了异常。

我该怎么办?

我的代码是

 ThreadStart threadstatr = new ThreadStart(Function_1);
 ThreadStart threaProgress = new ThreadStart(Function_2);
 Thread thread = new Thread(threadstatr);
 Thread threadpro = new Thread(threaProgress);
 thread.Start();
 threadpro.Start();
 thread.Join();
 threadpro.Join();

void Function_2()
    {
        int coun = ((Convert.ToInt32(label1.Text)) / 100); //here label1 represents total no. of files
        for (int i = 0; i < coun; i++)
        {
            backgroundWorker1.ReportProgress(i);
        }
    }

异常是“输入字符串的格式不正确。”因为标签没有机会自我更新

【问题讨论】:

  • 你试过什么?显示一些代码?为什么你还有一个单独的线程用于进度条?
  • 同上,还有什么例外?
  • ThreadStart threadstatr = new ThreadStart(Function_1); ThreadStart threaProgress = new ThreadStart(Function_2);线程 thread = new Thread(threadstatr);线程 threadpro = new Thread(threaProgress);线程.Start(); threadpro.Start();线程.Join(); threadpro.Join();
  • “输入字符串的格式不正确。”,很明显 label1.text 不是数字。
  • 那些变量名让我想伤害自己...

标签: c# .net desktop-application


【解决方案1】:

嗯,它似乎比它需要的要复杂一些。使用 BackgroundWorker 应该使您能够完全避免原始 Thread 对象(ThreadStart 等)。

您有一个主应用程序/UI 线程,您的进度条在其中被实例化。
您想使用 BackgroundWorker 启动线程来完成工作 - 通过将您的工作(搜索文件)方法连接到 BackgroundWorker.DoWork 事件。
该方法可以使用BackgroundWorker.ReportProgress 方法将进度报告回UI 线程。 您的 UI 线程可以通过处理 BackgroundWorker.ProgressChanged 事件来响应进度(增量进度控制)。
在创建 BackgroundWorker 时不要忘记设置 BackgroundWorker.WorkerReportsProgress = true

您可以通过查看 BackgoundWorker 的文档来获取更多详细信息。

【讨论】:

    【解决方案2】:

    不要重复另一个答案和我的评论,但您似乎没有在听。

    删除线程。您的代码中没有 ThreadStart。

    并且不要从后台读取 UI 控件。
    传递数据:

    backgroundWorker1.RunWorkerAsync(numberToCompute);
    

    使用 BackgroundWorker。

    如果您愿意,这正是您所需要的。

    BackgroundWorker Class

    【讨论】:

      猜你喜欢
      • 2012-08-24
      • 2023-01-31
      • 1970-01-01
      • 2012-12-04
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      相关资源
      最近更新 更多