C# 一种不阻塞的 MessageBox 用法
主界面一个测试按钮。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp2_TestMessageBox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
m_process = new TProcess();
m_process.MessageBoxShowHandler = MessageBoxShow;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private TProcess m_process;
private void button1_Click(object sender, EventArgs e)
{
m_process.Start();
}
public DialogResult MessageBoxShow(string msg)
{
return MessageBox.Show(msg, "hello", MessageBoxButtons.YesNo);
}
}
class TProcess
{
public TProcess()
{
}
public Func<string, DialogResult> MessageBoxShowHandler;
public void Start()
{
Thread m_Th = new Thread(new ThreadStart(() => { MessageBoxShow("Hello Hi 你好!"); }));
m_Th.IsBackground = true;
m_Th.Start();
}
public void MessageBoxShow(string msg)
{
MessageBox.Show("第一");
DialogResult result = DialogResult.None;
Task.Run(() =>
{
if (MessageBoxShowHandler != null)
{
result = /*MessageBoxShowHandler(msg)*/MessageBox.Show(msg, "Task 内部测试", MessageBoxButtons.YesNo);
}
});
Task.Run(() =>
{
if (MessageBoxShowHandler != null)
{
//result = MessageBoxShowHandler(msg);
result = (DialogResult)(MessageBoxShowHandler?.Invoke(msg + "1"));
}
});
while (true)
{
if (result == DialogResult.Yes)
{
Console.WriteLine("Yes");
break;
}
}
}
}
}
如果这里多次调用,会弹出多个窗口,如果在一个循环里面要注意处理。
Task.Run(() =>
{
if (MessageBoxShowHandler != null)
{
result = /*MessageBoxShowHandler(msg)*/MessageBox.Show(msg, "Task 内部测试", MessageBoxButtons.YesNo);
}
});
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了