C#如何取消执行方法

MiB*_*Bol 4 c# multithreading delegates thread-safety

我有一个委托方法在我的应用程序中运行繁重的进程(我必须使用MS Framework 3.5):

private delegate void delRunJob(string strBox, string strJob);
Run Code Online (Sandbox Code Playgroud)

执行:

    private void run()
    {
        string strBox = "G4P";
        string strJob = "Test";

        delRunJob delegateRunJob = new delRunJob(runJobThread);
        delegateRunJob.Invoke(strBox, strJob);
    }
Run Code Online (Sandbox Code Playgroud)

在该方法的某些部分 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 ...
}
Run Code Online (Sandbox Code Playgroud)

我想让用户取消整个过程.

怎么能实现这个?我尝试了一些方法; 但我陷入了同样的境地; 当这条特定的线路运行时,我无法停止该过程.

Phi*_*yck 6

您必须研究异步和等待机制,而不是使用委托机制.当您了解此机制后,您可以转到canceltoken.可以在此处找到执行这两项操作的示例:http: //blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-异步apis.aspx