gpt4 book ai didi

c# - 线程基础

转载 作者:太空狗 更新时间:2023-10-30 00:35:21 26 4
gpt4 key购买 nike

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;


namespace testThreads
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

}

private void Form1_Load(object sender, EventArgs e)
{

}

public void countToLots()
{
for (int i = 0; i < 10000000; i++)
{
textBox1.Text = "Counting to 10000000, value is " + i + Environment.NewLine;
}
}

public void countToZero()
{
for (int i = 10000000; i > 0; i--)
{
textBox2.Text = "Counting to 0, value is " + i + Environment.NewLine;
}
}

private void button1_Click(object sender, EventArgs e)
{
Thread countUp = new Thread(new ThreadStart(countToLots));
Thread countDown = new Thread(new ThreadStart(countToZero));
countUp.Start();
countDown.Start();
}

private void button2_Click(object sender, EventArgs e)
{
textBox3.Text = "Bobby bob bob " + Environment.NewLine;
}
}
}

我真的需要尝试掌握这个窍门——我只是不明白为什么我会收到错误消息背后的理论。有人可以帮帮我吗?

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.

最佳答案

UI 控件具有“线程亲和性”;他们不想除UI线程之外的任何东西;其中包括读写属性。对 .Text 的分配应从 UI 线程完成,方法是使用 InvokeBackgroundWorker

例如:

public void countToLots()
{
for (int i = 0; i < 10000000; i++)
{
// running on bg thread
textBox1.Invoke((MethodInvoker) delegate {
// running on UI thread
textBox1.Text = "Counting to 10000000, value is "
+ i + Environment.NewLine;
});
// running on bg thread again
}
}

但是注意这种线程切换是有开销的。您不应该在每次迭代时都回调 - 您应该(例如)每 [n] 次迭代更新 UI - 在上面,例如每 10000 次。

关于c# - 线程基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4943675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com