简体   繁体   English

WPF 异步任务错误未触发

[英]WPF async task errors not firing

Maybe I am completely lost here, but I am having the hardest time figuring out what is causing my tasks to exit prematurely and any attempts at error handling has failed so far.也许我在这里完全迷失了,但我很难弄清楚是什么导致我的任务过早退出,并且到目前为止任何错误处理尝试都失败了。 Issue is I am stepping through hundreds of directories in a file system so step debugging to find where I am failing is impossible, plus I need to be handling errors anyway.问题是我正在遍历文件系统中的数百个目录,因此不可能通过单步调试来找到我失败的地方,而且无论如何我都需要处理错误。 Here is what I have so far.这是我到目前为止所拥有的。

Button code triggered by WPF button.由 WPF 按钮触发的按钮代码。

private void BtnCopy_Click(object sender, RoutedEventArgs e)
{
Dispatcher.Invoke(() => { BtnBrowse.IsEnabled = false; BtnCopy.IsEnabled = false; });

var task = Task.Run(() =>
{
  try
  {
    _ = RunCopy();
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
  }
});
}
task.ContinueWith((t) => { Dispatcher.Invoke(() => { BtnBrowse.IsEnabled = true; BtnCopy.IsEnabled = true; }); });

This message box never shows.此消息框永远不会显示。 In my RunCopy code I am cycling through the folders in a directory.在我的 RunCopy 代码中,我正在循环浏览目录中的文件夹。

private async Task RunCopy()
{
foreach (var folder in firstDirInfo.GetDirectories())
{
  if (folder.Name.Contains(customerNumber))
  {
    await CopyTask(firstDirInfo + @"\" + folder, customerNumber);
  }
}
}

CopyTask is the event that is eventually erroring out. CopyTask 是最终出错的事件。

private async Task CopyTask(string directory, string customerNumber)
{
var dirInfo = new DirectoryInfo(directory);

            //Create root folder
            var createFolder = copyToDir + @"\" + dirInfo.Name;
            if (!Directory.Exists(createFolder))
                Directory.CreateDirectory(createFolder);

            foreach (var folder in dirInfo.GetDirectories())
            {
                var sourceFolder = directory + @"\" + folder.Name; 
                var targetFolder = createFolder + @"\" + folder.Name;

                //Create target path if it doesn't exist
                if (!Directory.Exists(targetFolder))
                    Directory.CreateDirectory(targetFolder);

                //Now Create all of the directories
                foreach (var dirPath in Directory.GetDirectories(sourceFolder, "*", SearchOption.AllDirectories))
                {
                    if (!Directory.Exists(dirPath))
                        Directory.CreateDirectory(dirPath);
                }

                //Gather copy information
                foreach (var newPath in Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories))
                {
                    masterDic.Add(newPath, newPath.Replace(sourceFolder, targetFolder));
                }
            }
}

The purpose if this is to eventually run an async file copy, I am just collecting the file information and creating directories first so I can handle the progress bar later.如果这样做的目的是最终运行异步文件副本,我只是先收集文件信息并创建目录,以便稍后处理进度条。 It errors out in the poorly name CopyTask Task.它在名称不佳的 CopyTask 任务中出错。

Ultimately I am just trying to figure out how to handle errors.最终我只是想弄清楚如何处理错误。 Any guidance would help greatly.任何指导都会有很大帮助。 Thanks!谢谢!

Found one error immediatelly:立即发现一个错误:

try
{
    _ = RunCopy();
}

Must be awaited or the Try block can't capture any exceptions in the task.必须等待,否则 Try 块无法捕获任务中的任何异常。 And BtnCopy_Click must become async.并且 BtnCopy_Click 必须变为异步的。

private async void BtnCopy_Click(object sender, RoutedEventArgs e)
{
    Dispatcher.Invoke(() => { BtnBrowse.IsEnabled = false; BtnCopy.IsEnabled = false; });

    try
    {
      await RunCopy();
    }
    catch (Exception ex)
    {
      MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }

    Dispatcher.Invoke(() => { BtnBrowse.IsEnabled = true; BtnCopy.IsEnabled = true; });   

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

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