异步操作显示错误的文件

时间:2016-05-10 15:00:48

标签: c# wpf asynchronous task

我正在尝试在aysnc操作中将项添加到ObservableCollection。如果我运行该应用程序,则该集合没有正确的文件。如果我单步执行它,我会看到添加了正确的文件,这显然显示了计时问题。麻烦是我无法弄清楚如何解决它。除此之外,其他一切都按照我的预期运作。

有人可以向我解释我做错了什么以及如何修复它以便将正确的文件名写入ObservableCollection?

private void ChangeFile(INotificationComplete notification)
{
FileInfo currentFileInfo = null;

var destinationImageFilename = string.Empty;

var imageDestinationFolder = Path.Combine(messageBrokerInstance.GetProgramPath("LevelThreeFilesWebLocation", this.SelectedPlatform), "images");

var fileDestinationFolder = Path.Combine(messageBrokerInstance.GetProgramPath("LevelThreeFilesWebLocation", this.SelectedPlatform));

try
{
    Task.Factory.StartNew((Action)delegate
    {
        string[] files = null;

        if (directoryInfo.Exists)
        {
            files = Directory.GetFiles(directoryInfo.FullName, @"*.htm", SearchOption.TopDirectoryOnly);
        }

        foreach (string file in files)
        {
            currentFileInfo = new FileInfo(file);

            **// bunch of code

            // I've found what I want and now am ready to write the file  
            // and add the filename to the collection the user sees.**


            if (writeFile)
            {
                var fileDestination = Path.Combine(fileDestinationFolder, currentFileInfo.Name);

                File.WriteAllLines(webFileDestination, fileArray);

                **// Correct file was written but the wrong filename
                // is added to the collection.**
                // If I step through this, the correct filename is added.
                UIDispatcher.Current.BeginInvoke((Action)delegate
                {
                    this.ChangedFiles.Add(currentFileInfo.Name);   // ChangedFiles is an ObservableCollection<string>
                });
            }
        }

        WaitAnimationNotification offNotification = new WaitAnimationNotification()
        {
            IsWaitAnimationOn = false,
            WaitAnimationMessage = "Please wait while the operation completes..."
        };

        WaitAnimationNotification waitNotification = notification as WaitAnimationNotification;

        if (waitNotification.IsWaitAnimationOn)
        {
            this.SendMessage("ToggleWaitAnimation", new NotificationEventArgs<WaitAnimationNotification, INotificationComplete>("ToggleWaitAnimation", offNotification));
        }
    });
}
}

1 个答案:

答案 0 :(得分:0)

我不知道UIDispatcher.Current是什么,但正确使用的调度程序是Application.Current.Dispatcher很容易在后台线程上无意中启动一个单独的调度程序 - 这将为您提供所看到的行为。 Application.Current.Dispatcher将成为主应用程序消息泵

的正确调度程序