- 使用单例模式确保只有一个任务正在运行。
public class BackgroundTaskService {
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1);
private bool _isRunning;
public async Task StartAsync() {
if (!_isRunning) {
await _semaphore.WaitAsync();
try {
if (!_isRunning) {
_isRunning = true;
// Start background task here
}
} finally {
_semaphore.Release();
}
}
}
public void Stop() {
if (_isRunning) {
_isRunning = false;
// Stop background task here
}
}
}
- 使用 CancellationTokenSource 取消正在运行的任务,然后启动新任务。
public static class BackgroundTask {
private static CancellationTokenSource _cancellationTokenSource;
public static void Start() {
if (_cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested) {
_cancellationTokenSource.Cancel();
// Wait for previous task to exit
try {
Task.Delay(1000).Wait();
} catch (AggregateException) {
}
}
_cancellationTokenSource = new CancellationTokenSource();
Task.Run(() => {
while (true) {
if (_cancellationTokenSource.IsCancellationRequested) {
break;
}
// Do work here
Thread.Sleep(1000);
}
}, _cancellationTokenSource.Token);
}
public static void Stop() {
if (_cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested) {
_cancellationTokenSource.Cancel();
// Wait for task to exit
try {
Task.Delay(1000).Wait();
} catch (AggregateException) {
}
}
}
}