C#,使用Task.Run-to-Run方法,但代码未执行
您好,我正在尝试在WPF应用程序的后台使用单独的任务来运行方法,我有两个任务使用Task.run来启动其他类中的其他方法。第一个非常好用。我用的是c# 单击按钮后调用:C#,使用Task.Run-to-Run方法,但代码未执行,c#,wpf,task,task-parallel-library,C#,Wpf,Task,Task Parallel Library,您好,我正在尝试在WPF应用程序的后台使用单独的任务来运行方法,我有两个任务使用Task.run来启动其他类中的其他方法。第一个非常好用。我用的是c# 单击按钮后调用: try { Task loading = Task.Run(() => cleaner.startCleanProcess()); txt_Progress.Text += "The data clean is in progress \r";
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
}
该方法位于cleaner类中,如下所示:
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);
}
}
有没有人发现这个设置有什么直接的问题?当我逐步完成时,任务显示它正在运行,但什么也没有发生(这些方法由于明显的原因而被简化),但据我所知,第二个方法从未真正启动过。断点不会被击中,文件永远不会被写入。如果我直接启动这个方法,而不是使用任务,它会运行得很好。
我只是问是否有人能看到我是否设置了这个错误,因为我整天都被困在上面,担心我的大脑可能已经停止工作了
感谢您抽出时间,正如@JSteward和@Ron Beyer所说,您遇到了一个跨线程问题。您应该在debug中运行代码,并查看跨线程错误 为了避免这种情况,您可以做的一件事是获取变量中的文本,并将该变量传递到
Task.Run()
方法中
var batchFilePath = txt_BatchFilePath.Text;
Task updating = Task.Run(() => newUpdateManager.RunUpdate(batchFilePath));
Task update=Task.Run(()=>newUpdateManager.RunUpdate(txt_BatchFilePath.Text))代码>->字符串batchFilePath=txt\u batchFilePath.Text;任务更新=任务.Run(()=>newUpdateManager.RunUpdate(batchFilePath))代码>?首先从默认上下文访问ui元素…Text
。你试过调试这个吗?你有一个跨线程问题。你捕捉异常不够好。在RunUpdate中有try-catch
,但在从非UI线程访问txt\u batchFilePath.Text
时,在此之前会引发异常。这个异常没有被注意到,因此-RunUpdate从未真正运行过。