Thread 您所在的位置:网站首页 _threadstart_new_thread Thread

Thread

2023-09-15 15:50| 来源: 网络整理| 查看: 265

"So you would favor number a, right?"

Yes, less code to write, easier to read.

"Can you give an example with ManualReset and Cancellation executed by a ButtonClick event."

Here's the earlier code modified to use an event. The "StopIt" method can be called within a button handler or wherever you need it. Actually it is so simple it could be the button handler (except the function signature isn't correct).

private ManualResetEvent _cancelThread = new ManualResetEvent(false); private void StopIt () { _cancelThread.Set(); } private void StartIt () { var thread = new Thread(DoSomething); thread.IsBackground = true; //Ensure terminate event is reset _cancelThread.Reset(); thread.Start(); } protected void DoSomething () { Thread.CurrentThread.Name = "MyThread.DoSomething-" + Thread.CurrentThread.ManagedThreadId; for (int i = 0; i < 10000; i++) { Thread.Sleep(100); if (_cancelThread.WaitOne(0)) return; } }

Note that the StopIt method doesn't wait for the thread to terminate. If you wanted to do that then you'd need to promote the thread variable to a field and then wait on it after cancel.

Also note that for Winforms if you want to support progress indication and/or cancellation then you may consider using BackgroundWorker instead. This component is really designed for use in these types of situations. Tasks are better suited for other needs and threads are a very low level detail used only in the rare case where you need explicit control over the threads (like a TCP server).

Michael Taylor http://www.michaeltaylorp3.net



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有