2016-05-10 3 views
1

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

答えて

0

私はUIDispatcher.Currentが何であるか知らないが、使用する正しいディスパッチャは、それが意図せずにバックグラウンドスレッドで個別のディスパッチャをスピンアップするのは簡単ですApplication.Current.Dispatcherです - あなたが参照して動作を与えるであろう。 Application.Current.Dispatcherは、メインのアプリケーションメッセージポンプの正しいディスパッチャになります。

+0

UIDispatcher.Currentは、Application.Current.DispatcherのSimpleMVVMラッパーです。 –

関連する問題