C#,使用 Task.Run 到 运行 方法,但代码未执行

C#, Using Task.Run to run method, but the code is not executing

您好,我正在尝试在 WPF 应用程序的后台对 运行 方法使用单独的任务,我有 2 个任务使用 Task.Run 来触发其他 class 中的其他方法]是的。第一个绝对没问题。我正在使用 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
        } 

该方法在清洁器中 class 并且看起来像:

     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);

                }
     }

有没有人碰巧发现此设置有任何问题?当我逐步完成时,任务显示它是 运行ning,但没有任何反应(出于明显的原因简化了这些方法),但据我所知,第二种方法从未真正启动过。断点不会被击中,文件永远不会被写入。如果我直接关闭该方法而不是使用 Task,它 运行 很好而且花花公子。 我只是问是否有人能看到我是否设置错了,因为我整天都被困在上面,担心我的大脑可能已经停止了。

谢谢你的时间

正如@JSteward 和@Ron Beyer 所说,您遇到了跨线程问题。您应该 运行 调试代码并查看跨线程错误。

为避免这种情况,您可以做的一件事是获取变量中的文本并在 Task.Run() 方法中传递该变量。

var batchFilePath = txt_BatchFilePath.Text;
Task updating = Task.Run(() => newUpdateManager.RunUpdate(batchFilePath));