嘿,我是 C# 新手,请帮忙。
我正在编写一个对文件中的数据进行排序的程序,这是一个耗时的过程,所以我认为我应该在一个单独的线程中运行它,因为它有很多步骤,所以我为它创建了一个新类。问题是我想在主 GUI 中显示进度,我知道我必须使用 Invoke 函数,但问题是表单控制变量在这个类中是不可访问的。我应该怎么办 ??????

示例代码:

public class Sorter
{
    private string _path;
    public Sorter(string path)
    {
        _path = path;
    }

    public void StartSort()
    {
        try
        {
                 processFiles(_path, "h4x0r"); // Just kidding
        }
        catch (Exception e)
        {
            MessageBox.Show("Error: " + e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void processFiles(string Dir, string[] key)
    {
        /* sorting program */

    }

它被用作
    public partial class Form1 : Form
    {
        Sorter sort;
        public Form1()
        {
            InitializeComponent();
        }

        private void browseBtn_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                textBox1.Text = folderBrowserDialog1.SelectedPath;
        }

        private void startBtn_Click(object sender, EventArgs e)
        {
            if (startBtn.Text == "Start Sorting")
            {
   Thread worker = new Thread(new ThreadStart(delegate() {
                sort = new Sorter(textBox1.Text);
                sort.StartSort(); }));
                worker.start();
            }
            else
                MessageBox.Show("Cancel");//TODO: add cancelling code here
        }
    }

请帮忙..

最佳答案

向正在执行多线程工作的类添加一个事件,该事件在进度更改时触发。让您的表单订阅此事件并更新进度条。

注意 ProgressEventArgs 是一个继承 EventArgs 的小类,并且有一个 Integer 表示进度。

// delegate to update progress
public delegate void ProgressChangedEventHandler(Object sender, ProgressEventArgs e);

// Event added to your worker class.
public event ProgressChangedEventHandler ProgressUpdateEvent

// Method to raise the event
public void UpdateProgress(object sender, ProgressEventArgs e)
{
   ProgressChangedEventHandler handler;
   lock (progressUpdateEventLock)
   {
      handler = progressUpdateEvent;
   }

   if (handler != null)
      handler(sender, e);
}

关于c# - 从另一个类 c# 更新 gui,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5193342/

10-11 22:58
查看更多