Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

multithreading - How to stop current thread automatically(forcefully) in c# console Application


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...