簡體   English   中英

UI在重度計算時凍結

[英]UI freezes on heavy calculation

我正在將大量文件加載到內存中,但在此計算中,我的應用程序已凍結。

知道我的代碼有什么問題嗎?

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

}

我將你的樣本轉換成這樣的東西:

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

我不確定它是否是您的問題的原因,但是您在后台工作程序的回調中設置了args.Handled ,因此它將在drop事件處理程序返回后調用。 由於設置得太晚,它不會產生預期的效果,並且可能會在事件處理中弄亂一些東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM