.NET: How to have background thread signal main thread data is available?

后端 未结 7 1968
终归单人心
终归单人心 2021-02-14 04:54

What is the proper technique to have ThreadA signal ThreadB of some event, without having ThreadB sit blocked waiting for an e

7条回答
  •  广开言路
    2021-02-14 05:12

    Here's a code sample for the System.ComponentModel.BackgroundWorker class.

        private static BackgroundWorker worker = new BackgroundWorker();
        static void Main(string[] args)
        {
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.ProgressChanged += worker_ProgressChanged;
            worker.WorkerReportsProgress = true;
    
            Console.WriteLine("Starting application.");
            worker.RunWorkerAsync();
    
            Console.ReadKey();
        }
    
        static void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            Console.WriteLine("Progress.");
        }
    
        static void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            Console.WriteLine("Starting doing some work now.");
    
            for (int i = 0; i < 5; i++)
            {
                Thread.Sleep(1000);
                worker.ReportProgress(i);
            }
        }
    
        static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Console.WriteLine("Done now.");
        }
    

提交回复
热议问题