C#从不同的类/线程更新UI

时间:2017-04-11 05:54:26

标签: c# multithreading winforms

早上好,我正在尝试用C#编写一些应用程序,我想从另一个线程和类更新UI(在这种情况下是一个进度条)。

但是我无法让它工作,我用Google搜索并搜索,但我担心我只是不明白。我有一个Windows窗体应用程序,当我单击一个按钮时我启动一个线程,在这个线程的某个地方我想更新我的UI。

我得到: 非静态字段,方法或属性需要对象引用 或者由不同线程创建的对象方向的东西。 (在我尝试在fileReader中调用 Form1.UpdateProgressBar(value); 的位置)。

我没有面向对象编程的经验,我通常坚持使用C.如果有人能告诉我正确的方法,我会非常高兴。

Edit_1:好吧..错误的组合,到目前为止,如果我没有静态问题,答案可能会有所帮助。通过使整个类静态来修复静态问题会自行创建另外X个错误,包括:

静态类不能包含实例构造函数

namespace TestCode
{

  public partial class Form1 : Form
  {
    static fileReader SourceReader;
    public Thread SearchThread { get; set; }

    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        folderBrowserDialog1.ShowDialog();
        Console.WriteLine(folderBrowserDialog1.SelectedPath);

        this.SearchThread = new Thread(new ThreadStart(this.ThreadProcSafe));
        this.SearchThread.Start();
    }


    public void UpdateProgressBar( int value)
    {

       progressBar1.Value =value;

    }

    private void ThreadProcSafe()
    {
        SourceReader = new fileReader(folderBrowserDialog1.SelectedPath);
    }
  }
}

第2课:

     namespace TestCode
     {
         class fileReader
         {

             public fileReader(String path)
             {
                int value = 20;
                /*Do some stuff*/
                  Form1.UpdateProgressBar(value);

             }

          }

     }

2 个答案:

答案 0 :(得分:0)

检查是否需要调用并且需要inf,然后使用控件Invoke函数:

public void UpdateProgressBar( int value)
{
   if(progressBar1.InvokeRequired){
       progressBar1.Invoke(new MethodInvoker(() => progressBar1.Value=value));
   }else{
       progressBar1.Value =value;
   }
}

答案 1 :(得分:-1)

尝试从另一个类修改UI时,可以使用MethodInvoker:

ProgressBar progressBar = Form1.progressBar1;
MethodInvoker action = () => progressBar.Value = 80;
progressBar.BeginInvoke(action);

虽然你可以在另一个线程(例如Task)中使用它时使用它:

progressBar1.Invoke((Action)(() => progressBar1.Value=50))

但请考虑您帖子中的评论。它不需要依赖于Forms

中的fileReader

旁注:我不知道你怎么没有在这里找到你的问题:

how to update a windows form GUI from another class?

How to update the GUI from another thread in C#?

相关问题