[英]How to stop execution of a method based on calling of another method in 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.