冗长任务:报告进度或在调用后控制执行

时间:2011-12-08 13:42:10

标签: c# callback

我编写了一个将DLL用于其目的的函数。存在此函数的类具有用于监视此函数状态的dll的回调以及必须在另一个类中使用的字段。 当我在目标类中调用此函数时,我必须连续获取此字段值(对于进度条)或在此回调中传递“暂停”,但它只能在函数完成执行时执行/  我怎么能这样做? 有我的代码。我需要通过进度条对话框取消引擎取消

 class LibWrap //containing the LONG process with dll
{
public bool cancelThisBoringProcess;
public int currentPecentage;
public delegate void  pfnCallback(int progress, out bool cancel);
public void showProgress(int progress, out bool cancel)
{
 cancel = cancelThisBoringProcess; 
 currentPecentage = progress;
} 
[DllImport("Lib.DLL", CallingConvention = CallingConvention.Cdecl)]
 public unsafe static extern byte* bufferOp(byte* data,pfnCallback del);
public unsafe  BitmapFrame engine(BitmapFrame incomingFrame)
{
//...
 fixed (byte* inBuf = incoming)
 {
var callback = new pfnCallback(showProgress);
byte* outBuf = bufferOp(inBuf, callback);//this is DLL function with callback to get out percentage //and pass cancel
      GC.KeepAlive(callback);
//....
}
}
}
class Main
{
void OnClick(object sender, RoutedEventArgs e)
{
ProgressDialog dlg = new ProgressDialog("");
LibWrap lwrap = new LibWrap();
DoWorkEventHandler handler = delegate { BitmapFrame bf = lwrap.engine(img)); };

            dlg.AutoIncrementInterval = 100;
            dlg.IsCancellingEnabled = true;
            dlg.Owner = Application.Current.MainWindow;
            dlg.RunWorkerThread(handler);
}
}

// ProgressDialog来自http://www.hardcodet.net/2008/01/wpf-progress-dialog

1 个答案:

答案 0 :(得分:2)

我想你提到过,但这里是回调模式:

void LongOperation(object someParam, Function<int, bool> callback)
{
      int progress = 0;
      while (progress++<100)
      {
          // lengthy operation:
          Thread.CurrentThread.Sleep(1);

          if (!callback(progress)) 
              break;
      } 
}

这也显示了如何使用回调来中断/取消长操作

bool alwaysCancelAt30Seconds(int progress)
{
     if ((DateTime.Now - startTime).TotalSeconds <= 30)
     {
          form1.lblProgress.Text = progress.ToString();
     } else
     {
          form1.lblProgress.Text = "canceled due to timeout!";
          return false;     // means 'abort'
     }
     return true;           // means 'continue'
}

  // call site:
  LongOperation(new [] { "some", "data" }, alwaysCancelAt30Seconds);