C# 如何终止正在运行的功能?

C# 如何终止正在运行的功能?,c#,callback,C#,Callback,我找到了一个,正在尝试在我的应用程序中使用它 除了单击“取消”和进度条对话框调用worker.CancelAsync()时,一切似乎都正常。当这种情况发生时,我的流程仍在等待结束 这很难理解,所以我正在粘贴我的代码。问题是:当progressbardialog调用worker.CancelAsync()时,如何完全终止正在运行的“引擎”函数 只需将LibWrap.cancelThisBoringProcess更改为TRUE。DLL中的循环将被中止。但是我不知道如何在lwrap.engine(im

我找到了一个,正在尝试在我的应用程序中使用它

除了单击“取消”和进度条对话框调用
worker.CancelAsync()时,一切似乎都正常。当这种情况发生时,我的流程仍在等待结束

这很难理解,所以我正在粘贴我的代码。问题是:当progressbardialog调用worker.CancelAsync()时,如何完全终止正在运行的“引擎”函数


只需将LibWrap.cancelThisBoringProcess更改为TRUE。DLL中的循环将被中止。但是我不知道如何在lwrap.engine(img))运行时实现它。因此,首先LibWrap.cancelThisBoringProcess=false,但当用户在ProgressDialog dlg上按CANCEL时,它必须为TRUE(存在OK)-但如何在lwrap中传递此值?我找到了解决方案,但它离idial远得多(我在ProgressDialog中添加了public LibWrap lbInst;字段,然后在worker.cancelThisBoringProcess()之前使lbInst.cancelThisBoringProcess=true;这是有效的。可能它不仅对我有用。如果有人有另一个方法,那就好了!
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); 
} 
}