简体   繁体   English

如何停止执行基于在 c# 中调用另一个方法的方法

[英]How to stop execution of a method based on calling of another method in c#

I have a startrecorder method which contains logic to do screen capture, after that I want to do some other activities when stoprecorder is called then startrecorder should break and stoprecorder should execute.我有一个 startrecorder 方法,其中包含执行屏幕捕获的逻辑,之后我想在调用 stoprecorder 时执行一些其他活动,然后 startrecorder 应该中断并且 stoprecorder 应该执行。 How to do that.怎么做。 Basically stop a method execution when another method is called.基本上在调用另一个方法时停止方法执行。 Here is an example.这是一个例子。

Class ABC()
{
    private void StartRecord()
    {
        Method1(); // lets assume it is defined in ABC
        Method2(); //// lets assume it is defined in ABC
    }
    private void StopRecord()
    {
         //Logic to stop record goes here
    }
}

Class XYZ()
{
    ABC obj= new ABC();
    obj.StartRecord();
    Demo();
    obj.StopRecord();
  }
}

So, I want to continuously execute the methods present inside StartRecord() until StopRecord() is called.所以,我想连续执行 StartRecord() 中存在的方法,直到调用 StopRecord()。 When StartMethod() is called, the methods inside it should keep on executing.当 StartMethod() 被调用时,它里面的方法应该继续执行。 Then Demo() should execute, then when StopRecord() is called, StartRecord()should break and StopRecord() should continue.然后 Demo() 应该执行,然后当 StopRecord() 被调用时, StartRecord() 应该中断并且 StopRecord() 应该继续。

Note- When StopRecord() is called, Demo() should NOT execute once more.注意 - 当 StopRecord() 被调用时,Demo() 不应再次执行。

Easiest way is to pass around a token.最简单的方法是传递一个令牌。 You poll this token to recognize cancellation.您轮询此令牌以识别取消。 You can use the CancellationTokenSource to implement this behavior.您可以使用CancellationTokenSource来实现此行为。

Note that your scenario only makes sense when StartRecord is executed in parallel.请注意,您的方案仅在并行执行StartRecord时才有意义。 Otherwise execution is synchronous and StopRecord would be only executed after StartRecord has completed.否则执行是同步的,并且StopRecord只会在StartRecord完成后执行。 The following code therefore executes StartRecord on a background thread:因此,以下代码在后台线程上执行StartRecord

class Abc
{
    private CancellationTokenSource CancellationTokenSource { get; set; }

    public void StartRecord()
    {
        // Dispose the previous instance. CancellationTokenSource can only be used once
        this.CancellationTokenSource?.Dispose();

        this.CancellationTokenSource = new CancellationTokenSource();

        // Start a background thread and continue execution.
        // Note that the OperationCanceledException thrown by the CancellationToken is handled by this Task object.
        // It converts the exception into the Task.Status == TaskStatus.Canceled. 
        // Therefore application won't halt.
        Task.Run(
            () => ExecuteRecording(this.CancellationTokenSource.Token), 
            this.CancellationTokenSource.Token);
    }

    private void ExecuteRecording(CancellationToken cancellationToken)
    {
        try
        {
            cancellationToken.ThrowIfCancellationRequested();

            // In case Method1 is long running, pass in the CancellationToken 
            Method1(cancellationToken); 

            cancellationToken.ThrowIfCancellationRequested();

            // In case Method2 is long running, pass in the CancellationToken 
            Method2(cancellationToken); 
        }
        catch (OperationCanceledException) // Catch is optional. Exception will be handled by the wrapping Task
        {
            // Handle cancellation 
            // e.g. roll back, clean up resources like delete temporary files etc.
        }
    }

    public void StopRecord()
    {
        try
        {
            // Try to cancel. CancellationTokenSource can be cancelable, NULL or disposed 
            this.CancellationTokenSource?.Cancel();

            // Do something after StartRecord was canceled
        }
        catch (ObjectDisposedException)  
        {
        }         
    }
}

Usage用法

class Xyz
{
    Abc obj = new Abc();
   
    // StartRecord will start a background thread, so that execution can continue.
    // Otherwise execution would wait until StartRecord has completed (synchronous execution)
    obj.StartRecord();

    Demo();
    obj.StopRecord();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM