網(wǎng)站首頁 編程語言 正文
最近項目要用到,窗體Form程序要在后臺開啟幾個子線程,負責和其他端進行通信,異步讀寫,并且來更改UI。在網(wǎng)上查了有Backgroundworker與Thread兩種方法。
1.Backgroundworker
BackgroundWorker是微軟的在.net Framwork中添加的一個組件,主要對線程的訪問提供了一種安全的方式。簡單的說就是對Thread的一次封裝。
首先介紹一下BackgroundWorker的相關屬性和方法:
屬性:
- WorkerReportsProgress:是否可以報告進度。
- WorkerSupportsCancellation:是否允許異步中止。
- IsBusy:是否在運行。
- CancellationPending:判斷BackgroundWorker是否已經(jīng)異步取消。
方法:
- RunWorkerAsync:開始執(zhí)行任務。觸發(fā)DoWork事件
- ReportProgress:異步提醒,觸發(fā)ProgressChanged事件,但是這個如果可以使用,必須設置WorkerReportsProgress為True
- CancelAsync:取消BackgroundWorker操作。
事件:
- DoWork:執(zhí)行RunWorkerAsync后觸發(fā),異步執(zhí)行的認為。
- ProgressChanged:執(zhí)行ReportProgress時觸發(fā),異步獲得進度。
- RunWorkerCompleted:線程結束時觸發(fā),主要有成功結束,發(fā)生異?;蛘呷∠麜r發(fā)生。
一個簡單的例子:
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來說,卻沒有線程暫停和繼續(xù)的方法。但是對于一般的來說,這些功能也是不用的,而且在微軟的文檔中還提到了,Thread的Resume和Suspend已經(jīng)不推薦使用。
一個簡單的例子:
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());//觸發(fā)事件
}
}
}
}
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.總結
當你執(zhí)行的任務較簡單,不需要復雜控制時使用BackgroundWorker,較為方便;當你要執(zhí)行的任務需要復雜控制(如線程同步)時,要自己 創(chuàng)建線程。畢竟,如果我們要實用多個線程,還需要往窗體中加好幾個BackgroundWorker控件。
原文鏈接:https://blog.csdn.net/qq_16739693/article/details/88740301
相關推薦
- 2022-12-30 python中的decode()與encode()深入理解_python
- 2022-11-22 GoLang?channel關閉狀態(tài)相關操作詳解_Golang
- 2022-11-24 React?hooks使用方法全面匯總_React
- 2022-10-17 C#使用WebSocket與網(wǎng)頁實時通信的實現(xiàn)示例_C#教程
- 2023-04-22 GO的range如何使用詳解_Golang
- 2022-07-01 python讀取nc數(shù)據(jù)并繪圖的方法實例_python
- 2022-07-10 初中級前端程序員必用且夠用的git命令同時推送到github/gitee及三種常用場景
- 2022-06-13 詳解Python如何利用Pandas與NumPy進行數(shù)據(jù)清洗_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支