2017-04-11 98 views
-1

早上好,我試圖在C#中編寫一些應用程序,我喜歡從另一個線程和類更新UI(這裏是進度條)。C#從不同的類/線程更新UI

但我只是無法讓它工作,我搜索了一下,但我恐怕我只是不明白。我有一個Windows窗體應用程序,當我點擊一個按鈕時,我開始一個線程,並且在這個線程中的某個地方我想更新我的UI。

我要麼得到: 一個對象引用是所必需的非靜態字段,方法或屬性 或東西在物體的方向通過不同的線程被創建。 (在我嘗試致電Form1.UpdateProgressBar(value); in fileReader的位置)。我沒有經驗的面向對象編程,我通常堅持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); 

      } 

      } 

    } 
+0

您的fileReader類不是st atic這就是爲什麼編譯器說你在調用它的構造函數之前需要對該類的引用。 –

+1

這是一個糟糕的設計。 'fileReader'不應該依賴於'Forms'。查看「Task」和「IProgress 」的用法以獲得更好的進度通知。示例:https://blogs.msdn.microsoft.com/dotnet/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis/ – user3185569

回答

-1

您可以使用MethodInvoker來嘗試修改來自其他類的UI,如下所示:

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

,而你可以在不同的線程(例如Task)工作時,使用此:

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

但考慮您的文章的評論。它並不需要依賴於FormsfileReader

附註:我不知道你怎麼沒在這裏找到自己的問題:

how to update a windows form GUI from another class?

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

0

檢查的invoke是必需的,需要inf然後使用控件調用功能:

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