gpt4 book ai didi

c# - 如何更正错误 "accessed from a thread other than the thread it was created on"?

转载 作者:太空狗 更新时间:2023-10-29 19:54:34 31 4
gpt4 key购买 nike

以下代码给出了以下错误。我想我需要 "InvokeRequired"。但是我不明白我该如何使用?

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

代码:

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

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

protected static DataSet dataset = null;
private void Form1_Load(object sender, EventArgs e)
{

}

private void timer1_Tick(object sender, EventArgs e)
{
SimulationFrameWork.MCSDirector run = new SimulationFrameWork.MCSDirector();
DataSet ds = run.Get();

if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i]["result"].ToString() == "0")
{
dataset = run.Get(int.Parse(ds.Tables[0].Rows[i]["ID"].ToString()));
WorkerObject worker =
new WorkerObject(
int.Parse(dataset.Tables[0].Rows[i]["ID"].ToString()),
int.Parse(dataset.Tables[0].Rows[i]["Iteration"].ToString()),
listBox1, timer1);
Thread thread1 = new Thread(new ThreadStart(worker.start));
thread1.Start();
}
}
}
}
}

public class WorkerObject
{
private int id;
private int nmax;
private ListBox list1;
private System.Windows.Forms.Timer timer1;

public WorkerObject(int _id, int _nmax, ListBox _list1,
System.Windows.Forms.Timer _timer1)
{
id = _id;
nmax = _nmax;
list1 = _list1;
timer1 = _timer1;
}
public void start()
{
timer1.Stop();
int i, idaire, j;
double pi = 0.0, x, y;

Random rnd = new Random();
for (i = 0; i < 100; i++)
{
idaire = 0;
for (j = 0; j < nmax; j++)
{
x = rnd.Next(1, 10000) / (double)10000;
y = rnd.Next(1, 10000) / (double)10000;
if (Math.Pow(x, 2) + Math.Pow(y, 2) <= 1.0)
idaire += 1;
}
pi = 4 * (double)idaire / (double)nmax;
nmax *= 10;

list1.Items.Add(
"Iterasyon:" +
nmax.ToString() +
" ----->" +
pi.ToString() +
"\n");
System.Threading.Thread.Sleep(100);
}
SimulationFrameWork.MCSDirector run = new SimulationFrameWork.MCSDirector();
run.Update(id, pi);
list1.Items.Add("\n\n islem bitti...");
}
}
}

最佳答案

这应该让你绕过它

private delegate void stringDelegate(string s);
private void AddItem(string s)
{
if (list1.InvokeRequired)
{
stringDelegate sd = new stringDelegate(AddItem);
this.Invoke(sd, new object[] { s });
}
else
{
list1.Items.Add(s);
}
}

只需调用 AddItem,这将在需要时使用委托(delegate)调用添加,否则它只会将项目直接添加到框中。

一次拍摄

关于c# - 如何更正错误 "accessed from a thread other than the thread it was created on"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/925044/

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