我编写了一个代码,用于在两个线程中同时对数组进行冒泡排序,使用事件(对于分配很重要)并在 WinForm 中。不幸的是,我在升序和降序操作文本更改的两个地方出现以下错误:
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'textBox2' accessed from a thread other than the thread it was created on.'
代码如下:
using System.Threading;
namespace _14
{
public partial class Form1 : Form
{
public delegate void ArrayHandler(int[] array);
public ArrayHandler Ascending;
public ArrayHandler Descending;
public string arrayText;
public int[] array1; public int[] array2;
public Form1()
{
InitializeComponent();
}
public void Ascending_Action(int[] array)
{
MessageBox.Show(Thread.CurrentThread.Name);
textBox2.Text=string.Join(" ", array.Select(x => x.ToString()).ToArray());
}
public void Function1()
{
Ascending += Ascending_Action;
int temp;
for (int i = 0; i < array1.Length; i++)
{
for (int j = i+1; j < array1.Length; j++)
{
if (array1[i]>array1[j])
{
temp = array1[i];
array1[i] = array1[j];
array1[j] = temp;
}
Ascending(array1);
Thread.Sleep(300);
}
}
}
public void Descending_Action(int[] array)
{
MessageBox.Show(Thread.CurrentThread.Name);
textBox3.Text = string.Join(" ", array.Select(x => x.ToString()).ToArray());
}
public void Function2()
{
Descending += Descending_Action;
int temp;
for (int i = 0; i < array2.Length; i++)
{
for (int j = i + 1; j < array2.Length; j++)
{
if (array2[i] < array2[j])
{
temp = array2[i];
array2[i] = array2[j];
array2[j] = temp;
}
Descending(array2);
Thread.Sleep(300);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
arrayText = textBox1.Text;
array1 = arrayText.Split(" ").Select(x => int.Parse(x)).ToArray(); array2 = array1;
textBox1.Visible = false;
textBox2.Visible = true;
textBox3.Visible = true;
button1.Visible = false;
Thread thread1 = new Thread(Function1);
Thread thread2 = new Thread(Function2);
thread1.Start();
thread2.Start();
}
}
}
我还检查了哪个线程访问了故障点,它返回了两个定制线程。虽然我不知道哪个线程是原始线程,也许有人可以在查看后澄清?
解决方案是将文本框放在方法调用程序包装中,如下所示:
textBox3.Invoke((MethodInvoker)delegate {
textBox3.Text = string.Join(" ", array2.Select(x => x.ToString()).ToArray());
});