C# 多線程更新界面的錯誤的解決方法
由于一個線程的程序,如果調(diào)用一個功能是阻塞的,那么就會影響到界面的更新,導(dǎo)致使用人員操作不便。所以往往會引入雙線程的工作的方式,主線程負責(zé)更新界面和調(diào)度,而次線程負責(zé)做一些阻塞的工作。
這樣做了之后,又會導(dǎo)致一個常見的問題,就是很多開發(fā)人員會在次線程里去更新界面的內(nèi)容。比如下面的例子:

在上面的例子里,創(chuàng)建Win forms應(yīng)用,然后增加下面的代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var thread2 = new System.Threading.Thread(WriteTextUnsafe);
thread2.Start();
}
private void WriteTextUnsafe() =>
textBox1.Text = "This text was set unsafely.";
}
}
這里就是使用線程來直接更新界面的內(nèi)容,就會導(dǎo)致下面的出錯:

這樣在調(diào)試的界面就會彈出異常,但是有一些開發(fā)人員不是去解決這個問題,而是去關(guān)閉開發(fā)工具的選項,不讓彈出這個界面?;蛘卟皇褂谜{(diào)試方式。
其實上面的代碼是有問題的,我們需要把它們修改為下面這種形式:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var threadParameters = new System.Threading.ThreadStart(
delegate { WriteTextSafe("This text was set safely."); });
var thread2 = new System.Threading.Thread(threadParameters);
thread2.Start();
}
public void WriteTextSafe(string text)
{
if (textBox1.InvokeRequired)
{
// Call this same method but append THREAD2 to the text
Action safeWrite = delegate { WriteTextSafe($"{text} (THREAD2)"); };
textBox1.Invoke(safeWrite);
}
else
textBox1.Text = text;
}
}
}
這樣問題,就得了解決。這里使用了委托的方式。
到此這篇關(guān)于C# 多線程更新界面的錯誤方法詳情的文章就介紹到這了,更多相關(guān)C# 多線程更新界面的錯誤方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# 從Excel讀取數(shù)據(jù)向SQL server寫入
這篇文章主要介紹了C# 從Excel讀取數(shù)據(jù)向SQL server寫入的方法,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
C#/VB.NET實現(xiàn)HTML轉(zhuǎn)為XML的示例代碼
可擴展標記語言(XML)文件是一種標準的文本文件,它使用特定的標記來描述文檔的結(jié)構(gòu)以及其他特性。本文將利用C#實現(xiàn)HTML轉(zhuǎn)為XML,需要的可以參考一下2022-06-06

