如何传递参数到我的线程

本文关键字:我的 线程 参数 何传递 | 更新日期: 2023-09-27 18:02:29

我用c#写了一个带有窗口的程序。

我有一个按钮,做一些事情(这并不重要到底是什么),它刷新窗口在他的循环(在button_click函数)(this.Invalidate(false);(我不用这个。刷新,因为我有一个groupBox,我不想刷新))。

当button_click函数工作时,我不能最小化窗口,窗口被"卡住"。

我试图到这个按钮的代码在一个不同的线程,但它有一些问题与处理参数从主要形式。假设我有这样的代码:

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*/
}

那么如何做到这一点作为一个线程,获得参数(progressBar1, groupBox1和someabel)?

如何传递参数到我的线程

你可以使用ParameterizedThreadStart Delegate接受type object作为参数。因此,您可以创建自己的类,其中包含3个属性(progressBar1, groupBox1和someelabel),并将该对象传递给您的线程,在那里您可以将其转换回您的类类型并做任何您想做的事情。

你刚刚改变了你的问题,我看到你想把中间部分放在单独的线程上,你想让这个线程与线程交互。记住在UI上只有一个(Main)线程可以处理UI,而不是工作线程。工作线程应该负责一些计算/工作,但不是UI交互(在你的情况下是ShowDialog)。你应该考虑改变你的逻辑,你的背景应该做什么。

阅读Ted patinson关于如何从另一个线程调用UI的从一个次要线程更新UI。在WindForms中,这并不容易,在WPF中要容易得多。

你可以试试这样做:

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*/
}

封装ProgressBar, GroupBox, Labels的类:

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;
}
}