UI在重度计算时冻结

时间:2011-12-04 09:22:35

标签: c# wpf dispatcher

我正在将大量文件加载到内存中,但在此计算中,我的应用程序已冻结。

知道我的代码有什么问题吗?

public void Drop(DragEventArgs args)
{
  BackgroundWorker worker = new BackgroundWorker();
  string fileName = IsSingleTextFile(args);
  if (fileName == null) return;
  worker.DoWork += (o, ea) =>
  {
    try
    {
      StreamReader fileToLoad = new StreamReader(fileName);
      string filecontent = fileToLoad.ReadToEnd();
      fileToLoad.Close();
      // providing the information to the UI thread

      Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
        new Action(() => SfmLogFile = filecontent));
    }
    catch (Exception)
    {
      throw;
    }
  };

  worker.RunWorkerCompleted += (o, ea) =>
  {
    args.Handled = true;
    IsBusy = false;
  };

  // Mark the event as handled, so TextBox's native Drop handler is not called.

  IsBusy = true;
  worker.RunWorkerAsync();

}

2 个答案:

答案 0 :(得分:2)

我将你的样本变成这样的东西:

public void Drop(DragEventArgs args)
{
  string fileName = IsSingleTextFile(args);
  if (fileName == null) return;
  // It is better to create worker after check for file name.
  BackgroundWorker worker = new BackgroundWorker();
  worker.DoWork += (o, ea) =>
  {
    try
    {
      string filecontent = ReadAllText(fileName);    
      ea.Result = fileContent;
    }
    catch (Exception)
    {
      throw;
    }
  };

  worker.RunWorkerCompleted += (o, ea) =>
  {
    var fileContent = ea.Result as string;
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
        new Action(() => SfmLogFile = filecontent));

    // if IsBusy propery is not on the UI thread, then you may leave it here
    // otherwise it should be set using the dispatcher too.
    IsBusy = false;
  };

  IsBusy = true;
  worker.RunWorkerAsync();
  // Mark the event as handled, so TextBox's native Drop handler is not called.    
  args.Handled = true;
}

答案 1 :(得分:1)

我不确定这是否是您的问题的原因,但是您在后台工作程序的回调中设置args.Handled,因此它将在drop事件处理程序返回后调用。由于设置太晚,它不会产生预期的效果,并且可能会在事件处理中弄乱一些东西。

相关问题