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

在上面的例子里,創(chuàng)建Win forms應用,然后增加下面的代碼:
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)容,就會導致下面的出錯:

這樣在調(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#中的Task.WaitAll和Task.WaitAny方法介紹
這篇文章介紹了C#中的Task.WaitAll和Task.WaitAny方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04
C# System.BadImageFormatException問題及解決
這篇文章主要介紹了C# System.BadImageFormatException問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
C#使用RichTextBox實現(xiàn)替換文字及改變字體顏色功能示例
這篇文章主要介紹了C#使用RichTextBox實現(xiàn)替換文字及改變字體顏色功能,結(jié)合實例形式洗了C#中RichTextBox組件文字替換及改變字體顏色相關(guān)操作技巧,需要的朋友可以參考下2019-02-02

