跨线程 操作Winform 主UI时的扩展方法
2021-12-16 13:32 咒语 阅读(90) 评论(0) 编辑 收藏 举报我们在写WinForm程序的时候会发现,你在非UI线程里的的更改UI里的对象时会抛出异常。
这个时候就会要求使用控件的跨线程判断与操作,一个一个的元素的去写太麻烦了。我写了个简单的扩展。
然后,就像只有一个线程一样的去操作吧。
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace System.Windows.Forms { public static class FormExtensions { public static void Push(this TextBox box, string message, TraceLevel level = TraceLevel.Info) { box.SafeChange(() => { if (box.Lines.Length > 5000) { box.Clear(); } box.AppendText($"[{DateTime.Now:HH:mm:ss fff}] [{level}] {message} {Environment.NewLine}"); }); } public static void Begin(this Button button) { button.SafeChange(() => { button.Tag = button.Text; button.Text = $"{button.Text} ..."; button.Enabled = false; }); } public static void End(this Button button) { button.SafeChange(() => { button.Text = (string)button.Tag; button.Enabled = true; }); } #region Contrl Thread Safe operation. public static void SafeChange(this Control control, Action action) { if (control.InvokeRequired) { control.Invoke(_safeChangeAction, control, action); } else { _safeChangeAction(control, action); } } private static Action<Control, Action> _safeChangeAction = SafeChangeForAction; private static void SafeChangeForAction(Control button, Action action) { action?.Invoke(); } #endregion } }
在主线程里操作时直接调用即可。
txtMessage.Push(msg);
或者你再包装成一个方法。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步