在漫长的操作期间显示消息?

时间:2014-07-25 14:23:20

标签: c# winforms

我有一小部分代码需要大约一分钟左右才能完成。在那个时候,没有迹象表明发生了什么。工作完成后,表单上的label.text中将显示一条消息。这是代码:

private void UpdateLesson()
{
    var bridgeBll = new BridgeBll();
    foreach (DataGridViewRow row in this.dataGridView1.Rows)
    {
        bridgeBll.UpdateLesson(row);
    }
    lblMessage.Text = "Saved at " + DateTime.Now.ToShortTimeString();
}

我想要做的是显示一个消息框,上面写着"保存......"然后在操作完成后关闭该消息框。但问题是,如果我打开一个消息框,工作将不会启动,直到用户手动关闭消息框并继续执行该程序。

我怎么能做这样的事情?

1 个答案:

答案 0 :(得分:0)

在表单上放置btnStart Button和label1 Label,并使用以下代码:

public partial class Form1 : Form
{

    MyAsyncClass worker;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        label1.Text = string.Format("Worker Started at {0}", DateTime.Now);
        if (worker == null)
        {
            worker = new MyAsyncClass();
            worker.NotifyCompleteEvent += worker_NotifyCompleteEvent;
        }
        worker.Start();
    }

    void worker_NotifyCompleteEvent(string message)
    {
        MessageBox.Show(string.Format("Worker completed with message: {0}", message));
    }

}

这是工人阶级:

public class MyAsyncClass
{

    public delegate void NotifyComplete(string message);
    public event NotifyComplete NotifyCompleteEvent;

    public void Start()
    {
        System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(DoSomeJob));
        t.Start();
    }

    void DoSomeJob()
    {
        //just wait 5 sec for nothing special...
        System.Threading.Thread.Sleep(5000);
        if (NotifyCompleteEvent != null)
        {
            NotifyCompleteEvent("My job is completed!");
        }
    }
}

您也可以在没有用户界面的情况下使用此原则。快乐的编码!