微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何基于C#中的另一个方法的调用来停止方法的执行

我有一个startrecorder方法,其中包含执行屏幕捕获的逻辑,此后,我想在调用stoprecorder时执行其他一些活动,那么startrecorder应该中断并且stoprecorder应该执行。 怎么做。当调用一个方法时,基本上停止方法的执行。 这是一个例子。

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

因此,我想连续执行StartRecord()中存在的方法,直到调用StopRecord()。 调用StartMethod()时,其中的方法应继续执行。然后执行Demo(),然后在调用StopRecord()时,StartRecord()应该中断,而StopRecord()应该继续。

注意-调用StopRecord()时,Demo()不应再执行一次。

解决方法

最简单的方法是传递令牌。您轮询此令牌以识别取消。您可以使用CancellationTokenSource来实现此行为。

请注意,只有StartRecord并行执行时,您的方案才有意义。否则,执行将是同步的,并且StopRecord仅在StartRecord完成之后才能执行。因此,以下代码在后台线程上执行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)  
        {
        }         
    }
}

用法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。