Thread timeout in c#

前端 未结 7 712
春和景丽
春和景丽 2021-01-11 18:41

I\'m new to threading in C#. Is there anyway of setting a timeout for a thread without blocking the calling thread (in C# 3.5)?

If not, is it logical to execute a fu

7条回答
  •  清歌不尽
    2021-01-11 19:26

    "Join member--> Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping." MSDN website.

    thrd1.Join() tell the calling thread to wait until the completion of the thrd1.

    My favorite solution is to make a small class which i'm able to control the execution of thread.

    public class MyClass
        {
            private bool _stop;
            private Thread _myThread;
    
            public void Stop()
            {
                _stop = true;
                //Will block the calling thread until the thread die
                _myThread.Join();
            }
    
            public void Run()
            {
                _stop = false;
                _myThread = new Thread(Work);
            }
    
            public void Work()
            {
                do
                {
    
                } while (!_stop);
            }
       }
    

提交回复
热议问题