C# 中怎么創(chuàng)建一個(gè)多線程窗體,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
10年積累的成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站設(shè)計(jì)后付款的網(wǎng)站建設(shè)流程,更有阿克陶免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
在winform程序開發(fā)中,計(jì)算機(jī)經(jīng)常會(huì)執(zhí)行一些比較耗時(shí)的任務(wù),如大量數(shù)據(jù)的查詢操作、較為復(fù)雜的業(yè)務(wù)處理等,這些任務(wù)往往需要耗時(shí)幾秒到幾十秒鐘的時(shí)間,在這些任務(wù)執(zhí)行期間winform程序窗體不再響應(yīng)任何鼠標(biāo)和鍵盤事件,出現(xiàn)假死狀態(tài),用戶體驗(yàn)很差。
一個(gè)比較好的解決辦法是,在這些任務(wù)執(zhí)行期間在界面前端顯示一個(gè)等待窗體,告訴用戶任務(wù)正在執(zhí)行中。
窗體中有一個(gè)PictureBox控件和兩個(gè)Lable控件,PictureBox控件的Image屬性為一張動(dòng)態(tài)圖片。
等待窗體源碼
1.2 提供訪問(wèn)等待窗體的接口
編寫類WaitFormService
using System;using System.Collections.Generic;using System.Text;using System.Threading;using System.Windows.Forms;namespace NavManager.Utils {////// Using Singleton Design Pattern/// 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(); }
看完上述內(nèi)容,你們掌握C# 中怎么創(chuàng)建一個(gè)多線程窗體的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!