我目前正在使用C#编写我的第一个程序,对这门语言非常陌生(之前只用过C)。我已经做了很多研究,但所有的答案都太笼统了,我根本无法让它正常运行。
所以这是我的(非常普遍的)问题:
我有一个WPF应用程序,它从用户填写的几个文本框中获取输入,然后使用这些输入进行大量计算。这些计算需要大约2-3分钟,因此我想更新进度条和文本块,告诉我当前状态如何。 此外,我需要存储用户的UI输入并将它们传递给线程,所以我有一个第三个类,我用它来创建一个对象,并希望将这个对象传递给后台线程。 显然,我会在另一个线程中运行计算,这样UI就不会冻结,但我不知道如何更新UI,因为所有计算方法都属于另一个类。 经过了很多研究,我认为最好的方法是使用dispatchers和TPL而不是backgroundworker,但老实说,我不确定它们是如何工作的,在尝试了其他答案20个小时后,我决定自己提问。
这是我程序的一个非常简单的结构:
public partial class MainWindow : Window
{
public MainWindow()
{
Initialize Component();
}
private void startCalc(object sender, RoutedEventArgs e)
{
inputValues input = new inputValues();
calcClass calculations = new calcClass();
try
{
input.pota = Convert.ToDouble(aVar.Text);
input.potb = Convert.ToDouble(bVar.Text);
input.potc = Convert.ToDouble(cVar.Text);
input.potd = Convert.ToDouble(dVar.Text);
input.potf = Convert.ToDouble(fVar.Text);
input.potA = Convert.ToDouble(AVar.Text);
input.potB = Convert.ToDouble(BVar.Text);
input.initStart = Convert.ToDouble(initStart.Text);
input.initEnd = Convert.ToDouble(initEnd.Text);
input.inita = Convert.ToDouble(inita.Text);
input.initb = Convert.ToDouble(initb.Text);
input.initc = Convert.ToDouble(initb.Text);
}
catch
{
MessageBox.Show("Some input values are not of the expected Type.", "Wrong Input", MessageBoxButton.OK, MessageBoxImage.Error);
}
Thread calcthread = new Thread(new ParameterizedThreadStart(calculations.testMethod);
calcthread.Start(input);
}
public class inputValues
{
public double pota, potb, potc, potd, potf, potA, potB;
public double initStart, initEnd, inita, initb, initc;
}
public class calcClass
{
public void testmethod(inputValues input)
{
Thread.CurrentThread.Priority = ThreadPriority.Lowest;
int i;
//the input object will be used somehow, but that doesn't matter for my problem
for (i = 0; i < 1000; i++)
{
Thread.Sleep(10);
}
}
}
我很感激如果有人能简单解释如何从测试方法内部更新UI。由于我刚接触C#和面向对象编程,过于复杂的答案可能会让我难以理解,但我会尽力学习。
此外,如果有更好的想法(例如使用backgroundworker或其他任何方法),我也很愿意了解。