C# 中怎么创建一个多线程窗体,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
在winform程序开发中,计算机经常会执行一些比较耗时的任务,如大量数据的查询操作、较为复杂的业务处理等,这些任务往往需要耗时几秒到几十秒钟的时间,在这些任务执行期间winform程序窗体不再响应任何鼠标和键盘事件,出现假死状态,用户体验很差。
一个比较好的解决办法是,在这些任务执行期间在界面前端显示一个等待窗体,告诉用户任务正在执行中。
窗体中有一个PictureBox控件和两个Lable控件,PictureBox控件的Image属性为一张动态图片。
等待窗体源码
1.2 提供访问等待窗体的接口
编写类WaitFormService
using System;using System.Collections.Generic;using System.Text;using System.Threading;using System.Windows.Forms;namespace NavManager.Utils {/// <summary>/// Using Singleton Design Pattern/// </summary>public class WaitFormService {public static void CreateWaitForm() { WaitFormService.Instance.CreateForm(); }public static void CloseWaitForm() { WaitFormService.Instance.CloseForm(); }public static void SetWaitFormCaption(string text) { WaitFormService.Instance.SetFormCaption(text); }private static WaitFormService _instance;private static readonly Object syncLock = new Object();public static WaitFormService Instance {get {if (WaitFormService._instance == null) {lock (syncLock) {if (WaitFormService._instance == null) { WaitFormService._instance = new WaitFormService(); } } }return WaitFormService._instance; } }private WaitFormService() { }private Thread waitThread;private WaitForm waitForm;public void CreateForm() {if (waitThread != null) {try{ waitThread.Abort(); }catch (Exception) { } } waitThread = new Thread(new ThreadStart(delegate() { waitForm = new WaitForm(); Application.Run(waitForm); })); waitThread.Start(); }public void CloseForm() {if (waitThread != null) {try{ waitThread.Abort(); }catch (Exception) { } } }public void SetFormCaption(string text) {if (waitForm != null) {try{ waitForm.SetText(text); }catch (Exception) { } } } } }
1.3 使用WaitFormService提供的接口
try{ WaitFormService.CreateWaitForm(); Assembly asmb = Assembly.GetExecutingAssembly(); Object obj = asmb.CreateInstance(className); Form frm = obj as Form;this.ShowMenu(frm); WaitFormService.CloseWaitForm(); }catch (Exception ex) { WaitFormService.CloseWaitForm(); }
看完上述内容,你们掌握C# 中怎么创建一个多线程窗体的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。