[英]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.