winform,子线程里messagebox如何模态阻止ui线程

在WinForms中,如果你想在子线程中显示一个MessageBox并阻止UI线程,可以使用InvokeBeginInvoke方法来确保MessageBox是在UI线程上显示的。这是因为WinForms控件不是线程安全的,所有的UI操作都应该在UI线程上进行。

以下是一个示例代码,展示如何在子线程中调用MessageBox,并确保它在UI线程上显示:

using System;
using System.Threading;
using System.Windows.Forms;

public class MainForm : Form
{
    private Button button;

    public MainForm()
    {
        button = new Button { Text = "Start Thread", Dock = DockStyle.Fill };
        button.Click += Button_Click;
        Controls.Add(button);
    }

    private void Button_Click(object sender, EventArgs e)
    {
        Thread thread = new Thread(ShowMessageBoxFromThread);
        thread.Start();
    }

    private void ShowMessageBoxFromThread()
    {
        // 模拟一些工作
        Thread.Sleep(2000);

        // 显示MessageBox
        this.Invoke((MethodInvoker)delegate
        {
            MessageBox.Show(this, "This is a message from a background thread.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        });
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}

在这个示例中:

  1. 当用户点击按钮时,启动一个新的线程执行ShowMessageBoxFromThread方法。
  2. ShowMessageBoxFromThread方法中,使用Thread.Sleep模拟一些工作,然后调用Invoke方法来在UI线程上显示MessageBox。

使用Invoke方法的好处是,它会在UI线程上同步执行委托,这样MessageBox会阻塞UI线程,直到用户关闭它。

如果你不需要等待MessageBox关闭后再继续执行其他操作,可以使用BeginInvoke方法,它会异步执行委托,不会阻塞调用线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金士顿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值