2011-07-16 83 views
1

我有一個程序,我用C#寫了一個窗口。我有一個按鈕,做一些事情(它並不重要),並刷新他的循環中的窗口(在button_click功能)(與this.Invalidate(假);(我不使用這個。刷新,因爲我有一個組框,我不想刷新))。如何將參數傳遞給我的線程?

當button_click函數工作時,窗口「卡住」,我不能最小化窗口。

我正試圖在不同的線程中使用此按鈕的代碼,但它有處理來自主窗體的參數的xome問題。 可以說我有這樣的代碼:

void button_click(object sender, EventArgs e) 
{ 
    /*want to put this in new thread*/ 
    progressBar1.Value = 0; 
    progressBar1.Maximum = int.Parse(somelabel_num.Text); 
    int i; 
    OpenFileDialog file = new OpenFileDialog(); 
    file.ShowDialog(); 
    if (file.FileName == "") 
     return; 
    Bitmap image = new Bitmap(file.FileName); 
    groupBox1.BackgroundImage = image; 

    for (i = 0; i < int.Parse(somelabel_num.Text); i++) 
    { 
     somelabel.Text = i; 
     this/*(main form)*/.Invalidate(false); 
     progressBar1.PerformStep(); 
    } 
    /*want that here the new thread will end*/ 
} 

所以如何做到這一點作爲獲取paremeters(progressBar1,groupBox1和somelabel)線程?

+0

線程共享內存空間。你有什麼問題?是產卵線程的代碼? – Rig

+0

請看我的編輯問題(我用兩個「/ ** /」編輯代碼(butten_click函數在MainForm中(項目的主窗體(一個Windows項目),並且沒有其他線程) – George

回答

1

您可以使用ParameterizedThreadStart Delegate接受類型對象作爲參數。因此,您可以創建包含3個屬性(progressBar1,groupBox1和somelabel)的自己的類,並將該對象傳遞給您的線程,然後將其轉換回您的類類型並執行任何您想要的操作。

你剛剛改變了你的問題,我發現你想把中間部分放在單獨的線程中,並且你希望那個線程與線程交互。記住在UI上只有一個(主)線程可以處理UI,而不是工作線程。工作者線程應該負責一些計算/工作,但不是UI交互(在你的情況下是ShowDialog)。你應該考慮改變你的背景應該做的邏輯。

閱讀Updating the UI from a Secondary Thread Ted Pattison關於如何從另一個線程調用UI。在WindForms中並不容易,在WPF中它更容易。

+0

謝謝你,我不知道該怎麼做,你可以編輯我的代碼(在問題中),因爲他會包含你建議的更改嗎? – George

+0

@George - 閱讀我的補充評論 –

+0

我想傳遞UI參數(progressBar1,groupBox1和一些標籤)到線程,並且比線程可以影響UI。 – George

0

你可以嘗試這樣的事情:

void button_click(object sender, EventArgs e) 
{ 
OpenFileDialog file = new OpenFileDialog(); 
file.ShowDialog(); 
if (file.FileName == "") 
    return; 
else 
{ 
    Bitmap image = new Bitmap(file.FileName); 
    Thread t = new Thread (new ParameterizedThreadStart(MyFunction)); 
    t.Start (new MyClass(progressbar1,groupbox1,label1,image)); 

} 
} 

目標函數是在這裏:

void MyFunction(object obj) 
{ 
MyClass myc= (MyClass) obj; 
myc._mypbar; /*can access varriables*/ 

/* your logic*/ 

} 

級封裝進度,分組框中,標籤:

public class MyClass 
{ 
public ProgressBar _mypbar; 
public GroupBox _mygpb; 
public Label _mylbl; 
public Image _myimg; 

public MyClass(ProgressBar pbar,GroupBox gpb, Label, lbl,Image img) 
{ 
this._mypbar = pbar; 
this._mygpb = gpb; 
this._mylbl = lbl; 
this._myimg = img; 
} 
} 
+0

它可能會顯示交叉線程異常。 – himanshu