網站首頁 編程語言 正文
最近項目要用到,窗體Form程序要在后臺開啟幾個子線程,負責和其他端進行通信,異步讀寫,并且來更改UI。在網上查了有Backgroundworker與Thread兩種方法。
1.Backgroundworker
BackgroundWorker是微軟的在.net Framwork中添加的一個組件,主要對線程的訪問提供了一種安全的方式。簡單的說就是對Thread的一次封裝。
首先介紹一下BackgroundWorker的相關屬性和方法:
屬性:
- WorkerReportsProgress:是否可以報告進度。
- WorkerSupportsCancellation:是否允許異步中止。
- IsBusy:是否在運行。
- CancellationPending:判斷BackgroundWorker是否已經異步取消。
方法:
- RunWorkerAsync:開始執行任務。觸發DoWork事件
- ReportProgress:異步提醒,觸發ProgressChanged事件,但是這個如果可以使用,必須設置WorkerReportsProgress為True
- CancelAsync:取消BackgroundWorker操作。
事件:
- DoWork:執行RunWorkerAsync后觸發,異步執行的認為。
- ProgressChanged:執行ReportProgress時觸發,異步獲得進度。
- RunWorkerCompleted:線程結束時觸發,主要有成功結束,發生異常或者取消時發生。
一個簡單的例子:
public partial class MainWindow : Window
{
private BackgroundWorker m_BackgroundWorker;// 申明后臺對象
public MainWindow()
{
InitializeComponent();
m_BackgroundWorker = new BackgroundWorker(); // 實例化后臺對象
m_BackgroundWorker.WorkerReportsProgress = true; // 設置可以通告進度
m_BackgroundWorker.WorkerSupportsCancellation = true; // 設置可以取消
m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWork);
m_BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);
m_BackgroundWorker.RunWorkerAsync(this);
}
void DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = sender as BackgroundWorker;
MainWindow win = e.Argument as MainWindow;
int i = 0;
while ( i <= 100 )
{
if (bw.CancellationPending)
{
e.Cancel = true;
break;
}
bw.ReportProgress(i++);
Thread.Sleep(1000);
}
}
void UpdateProgress(object sender, ProgressChangedEventArgs e)
{
int progress = e.ProgressPercentage;
label1.Content = string.Format("{0}",progress);
}
void CompletedWork(object sender, RunWorkerCompletedEventArgs e)
{
if ( e.Error != null)
{
MessageBox.Show("Error");
}
else if (e.Cancelled)
{
MessageBox.Show("Canceled");
}
else
{
MessageBox.Show("Completed");
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
m_BackgroundWorker.CancelAsync();
}
}
2.Thread
BackgroundWorker就是一個高級控件,方便使用Thread,后者是前者的靈魂或基礎
直接使用后者難度稍大,但換來的是靈活方便。
Thread的使用就比較麻煩了,對于尤其是對異步提醒來說,需要寫委托,代碼量是很多,但是對于BackgroundWorker來說,卻沒有線程暫停和繼續的方法。但是對于一般的來說,這些功能也是不用的,而且在微軟的文檔中還提到了,Thread的Resume和Suspend已經不推薦使用。
一個簡單的例子:
using System;
using System.Threading;
namespace ThreadsComm
{
public delegate void ReadParamEventHandler(string sParam);
class MyThread
{
public Thread thread1;
private static ReadParamEventHandler OnReadParamEvent;
public MyThread()
{
thread1 = new Thread(new ThreadStart(MyRead));
thread1.IsBackground = true;
thread1.Start();
}
public event ReadParamEventHandler ReadParam
{
add { OnReadParamEvent += new ReadParamEventHandler(value);}
remove{ OnReadParamEvent -= new ReadParamEventHandler(value);}
}
protected void MyRead()
{
int i = 0;
while (true)
{
Thread.Sleep(1000);
i = i + 1;
OnReadParamEvent(i.ToString());//觸發事件
}
}
}
}
using System;
using System.Windows.Forms;
namespace ThreadsComm
{
public partial class Form1 : Form
{
private static string param = "";
public Form1()
{
InitializeComponent();
MyThread thread1 = new MyThread();
thread1.ReadParam += this.OnRead;
}
private void OnRead(string sParam)
{
param = sParam;
Object[] list = { this,System.EventArgs.Empty};
this.lblShow.BeginInvoke(new EventHandler(LabelShow), list);
}
protected void LabelShow(Object o, EventArgs e)
{
this.lblShow.Text = param;
}
}
}
3.總結
當你執行的任務較簡單,不需要復雜控制時使用BackgroundWorker,較為方便;當你要執行的任務需要復雜控制(如線程同步)時,要自己 創建線程。畢竟,如果我們要實用多個線程,還需要往窗體中加好幾個BackgroundWorker控件。
原文鏈接:https://blog.csdn.net/qq_16739693/article/details/88740301
相關推薦
- 2022-12-14 Docker中容器數據卷詳解_docker
- 2022-04-17 <el-dropdown>按鈕點擊出來下拉菜單,點擊下拉菜單觸發事件
- 2022-11-27 C語言移除元素的三種思路講解_C 語言
- 2022-07-15 Android自定義view繪制表格的方法_Android
- 2023-03-03 Android獲取RecyclerView滑動距離方法詳細講解_Android
- 2022-08-06 詳解Android中motion_toast的使用_Android
- 2023-08-15 nginx 開啟壓縮
- 2022-06-19 mybatis-plus的sql語句打印問題小結_MsSql
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支