您好我正在尝试使用单独的任务在WPF应用程序的后台运行方法,我有2个任务使用Task.Run来触发其他类中的其他方法。第一个绝对精细。我正在使用c#
单击按钮后调用:
try
{
Task loading = Task.Run(() => cleaner.startCleanProcess());
txt_Progress.Text += "The data clean is in progress \r";
timer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(2)
};
timer.Tick += Timer_CleanProgress;
timer.IsEnabled = true;
}
catch (Exception ex)
{
do exception stuff
}
该方法位于clean类中,如下所示:
public void startCleanProcess()
{
try
{
do stuff
}
}
第二个是相同的设置,但方法内的代码永远不会执行
单击按钮时会调用:
try
{
Task updating = Task.Run(() => newUpdateManager.RunUpdate(txt_BatchFilePath.Text));
//newUpdateManager.RunUpdate(txt_BatchFilePath.Text);
txt_Progress.Text += "\rRunning the update through Middleware";
timer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(2)
};
timer.Tick += Timer_UpdateProgress;
timer.IsEnabled = true;
}
catch (Exception ex)
{
do exception stuff
}
RunUpdate方法设置如下:
public void RunUpdate(string filepath) {
try
{
string[] arraystring = { "hello", "world" };
File.WriteAllLines(filepath, arraystring);
}
}
有没有人碰巧看到这个设置立即出现了什么问题?当我单步执行时,任务说它正在运行,但没有任何反应(这些方法因为显而易见的原因而被简化)但据我所知,第二种方法从未实际开始。断点没有被击中,文件永远不会被写入。如果我直接启动方法而不是使用任务它运行正常和花花公子。 我只是问,是否有人可以看到我是否设置了这个错误,因为我整天被困在它上面,并担心我的大脑可能已经停止。
感谢您的时间
答案 0 :(得分:2)
正如@JSteward和@Ron Beyer所说,你有一个交叉线程问题。您应该在debug中运行代码并查看交叉线程错误。
为避免这种情况,您可以做的一件事就是将文本放在变量中,并在Task.Run()
方法中传递该变量。
var batchFilePath = txt_BatchFilePath.Text;
Task updating = Task.Run(() => newUpdateManager.RunUpdate(batchFilePath));