简体   繁体   中英

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. 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. When StartMethod() is called, the methods inside it should keep on executing. Then Demo() should execute, then when StopRecord() is called, StartRecord()should break and StopRecord() should continue.

Note- When StopRecord() is called, Demo() should NOT execute once more.

Easiest way is to pass around a token. You poll this token to recognize cancellation. You can use the CancellationTokenSource to implement this behavior.

Note that your scenario only makes sense when StartRecord is executed in parallel. Otherwise execution is synchronous and StopRecord would be only executed after StartRecord has completed. The following code therefore executes StartRecord on a background thread:

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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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