[C#]好用的WaitDialog

簡單的 Threading Wait Dialog

建立一個 Form 叫做 "WaitForm",讓他可以接受 action並且在背景執行

public partial class WaitForm : Form
{
    private readonly MethodInvoker method;

    public WaitForm(MethodInvoker action)
    {
        InitializeComponent();
        method = action;
    }

    private void WaitForm_Load(object sender, EventArgs e)
    {
        new Thread(() =>
        {
            method.Invoke();
            InvokeAction(this, Dispose);
        }).Start();
    }

    public static void InvokeAction(Control control, MethodInvoker action)
    {
        if (control.InvokeRequired)
        {
            control.BeginInvoke(action);
        }
        else
        {
            action();
        }
    }
}
當然要記得添加WaitForm_Load事件

使用:

private void btnShowWait_Click(object sender, EventArgs e)
{
    new WaitForm(() => /*Simulate long task*/ Thread.Sleep(2000)).ShowDialog();
}

相關系列文章:

留言

這個網誌中的熱門文章

[TCL] 基本語法與指令 - 2. TCL 語法

[TCL] 基本語法與指令 - 1. TCL 簡介

[TCL] 基本語法與指令 - 3. 資料型態