繁体   English   中英

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

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

嗨,我正在尝试使用单独的任务在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
        } 

该方法位于清洁器类内部,如下所示:

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

                }
     }

有没有人碰巧看到此设置有任何直接错误? 当我逐步执行该任务时,该任务将说明其正在运行,但是什么也没发生(出于明显的原因,这些方法被简化了),但据我所知,第二种方法从未真正启动过。 断点不会被命中,文件也不会被写入。 如果我直接启动该方法而不是使用Task,它将运行良好且花哨。 我只是问是否有人能看到我是否把这个设置错了,因为我整天都被困在上面,并担心我的大脑可能会停下来。

谢谢你的时间

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM