【发布时间】:2018-06-05 08:30:27
【问题描述】:
我编写了一个程序来保存传感器的 3 个不同位置。如果传感器回到保存的位置,我希望我的文本框的背景颜色为绿色。因为这些值的变化非常快速和精确,所以我决定只比较前 3 个值。所以我启动了我的程序并通过单击保存了一个位置。该位置已保存,文本框立即变为绿色,这很好,因为传感器仍处于此位置。但在那之后我得到了一个跨线程的例外,我不明白。我是 C# 的新手,我认为我在函数开始时通过调用解决了这个问题。
private void Safe_Position1(TextBox tBr1, TextBox tBi1, TextBox tBj1, TextBox tBk1, string[] text)
{
if (button3clicked == true)
{
if (!Dispatcher.CheckAccess())
{
textBox5.Dispatcher.BeginInvoke(new Action(() => Safe_Position1(tBr1, tBi1, tBj1, tBk1, text)));
}
if (!Dispatcher.CheckAccess())
{
textBox7.Dispatcher.BeginInvoke(new Action(() => Safe_Position1(tBr1, tBi1, tBj1, tBk1, text)));
}
if (!Dispatcher.CheckAccess())
{
textBox8.Dispatcher.BeginInvoke(new Action(() => Safe_Position1(tBr1, tBi1, tBj1, tBk1, text)));
}
if (!Dispatcher.CheckAccess())
{
textBox9.Dispatcher.BeginInvoke(new Action(() => Safe_Position1(tBr1, tBi1, tBj1, tBk1, text)));
}
else
{
tBr1.Text = text[0];
tBi1.Text = text[1];
tBj1.Text = text[2];
tBk1.Text = text[3];
button3clicked = false;
}
string firstthreetBr1 = new string(text[0].Take(3).ToArray());
string firstthreetBi1 = new string(text[1].Take(3).ToArray());
string firstthreetBj1 = new string(text[2].Take(3).ToArray());
string firstthreetBk1 = new string(text[3].Take(3).ToArray());
if (firstthreetBr1 == tBr1.Text.Substring(0,3)) <------ EXCEPTION HERE
{
tBr1.Background = Brushes.Green;
}
if (firstthreetBi1 == tBi1.Text.Substring(0, 3))
{
tBi1.Background = Brushes.Green;
}
if (firstthreetBj1 == tBj1.Text.Substring(0, 3))
{
tBj1.Background = Brushes.Green;
}
if (firstthreetBk1 == tBk1.Text.Substring(0, 3))
{
tBk1.Background = Brushes.Green;
}
}
}
谁能给我解释一下?
【问题讨论】:
-
什么异常?
-
在哪一行?
-
安全 vs 保存 vs 安全
-
每个
BeginInvoke()块都需要一个return,否则在调用BeginInvoke()之后,ifs 后面的代码仍然会被执行。 -
什么是异常信息
标签: c# multithreading exception