Instead of using Thread.Sleep
try use Task.Delay(int milliseconds, CancellationToken token)
. Task.Delay creates task that will complete after given delay. If token is cancelled during wait, it will throw exception and execution will stop. Also better to check before and after waiting for cancellation, because somebody could cancel execution while you were sleeping.
public void CheckDatabaseFieldStatus()
{
while (!Token.IsCancellationRequested)
{
Task.Delay(5000, Token).GetAwaiter().GetResult();
Token.ThrowIfCancellationRequested();
using (DbContext mydb= new DbContext())
{
if (mydb.Table.GetAll().Any(r => r.Status=="cancelling"))
{
TokenSource.Cancel();
}
}
}
}
Also I'm using GetAwaiter().GetResult()
instead of simple Wait()
because second option wraps exception. See this answer for explanation https://stackoverflow.com/a/38530225/10339675
In general it's better to use async
/await
instead of synchronously wait
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…