【发布时间】:2015-06-09 04:13:59
【问题描述】:
我有一个委托方法在我的应用程序中运行繁重的进程(我必须使用 MS Framework 3.5):
private delegate void delRunJob(string strBox, string strJob);
执行:
private void run()
{
string strBox = "G4P";
string strJob = "Test";
delRunJob delegateRunJob = new delRunJob(runJobThread);
delegateRunJob.Invoke(strBox, strJob);
}
在方法的某些部分runJobThread
我调用外部程序(SAP - 远程函数调用)来检索数据。该行的执行可能需要 1-30 分钟。
private void runJobThread(string strBox, string strJob)
{
// CODE ...
sapLocFunction.Call(); // When this line is running I cannot cancel the process
// CODE ...
}
我想让用户取消整个过程。
如何做到这一点?我尝试了一些方法;但我也陷入了同样的境地;当这条特定线路运行时,我无法停止该过程。
【问题讨论】:
-
您必须结合使用 async 和 await 以及取消令牌。
-
@PhilipStuyck,这会取消操作本身,还是只是取消等待,让操作成为孤立的并在后台运行?
-
这取决于您的代码,您必须检查长时间运行方法中的取消令牌,如果您看到任务被取消,则抛出任务取消异常。
-
“你的”代码是 sapLocFunction.Call(),它不需要 CancellationToken,除非有过载。
-
@glenebob 正确。也应该修改它以将取消标记作为参数。如果这是不可能的,那么就没有办法以优雅的方式进行取消。
标签: c# multithreading delegates thread-safety