In C# what is the recommended way of passing data between 2 threads?

后端 未结 9 860
长发绾君心
长发绾君心 2020-12-08 01:36

I have my main GUI thread, and a second thread running inside it\'s own ApplicationContext (to keep it alive, even when there is no work to be done). I want to call a method

9条回答
  •  孤城傲影
    2020-12-08 01:58

    The convenience of Control.BeginInvoke() is hard to pass up. You don't have to. Add a new class to your project and paste this code:

    using System;
    using System.Threading;
    using System.Windows.Forms;
    
    public partial class frmWorker : Form {
      public frmWorker() {
        // Start the worker thread
        Thread t = new Thread(new ParameterizedThreadStart(WorkerThread));
        t.IsBackground = true;
        t.Start(this);
      }
      public void Stop() {
        // Synchronous thread stop
        this.Invoke(new MethodInvoker(stopWorker), null);
      }
      private void stopWorker() {
        this.Close();
      }
      private static void WorkerThread(object frm) {
        // Start the message loop
        frmWorker f = frm as frmWorker;
        f.CreateHandle();
        Application.Run(f);
      }
      protected override void SetVisibleCore(bool value) {
        // Shouldn't become visible
        value = false;
        base.SetVisibleCore(value);
      }
    }
    

    Here's some sample code to test it:

      public partial class Form1 : Form {
        private frmWorker mWorker;
        public Form1() {
          InitializeComponent();
          mWorker = new frmWorker();
        }
    
        private void button1_Click(object sender, EventArgs e) {
          Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
          mWorker.BeginInvoke(new MethodInvoker(RunThisOnThread));
        }
        private void RunThisOnThread() {
          Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);
        }
    
        private void button2_Click(object sender, EventArgs e) {
          mWorker.Stop();
        }
      }
    

提交回复
热议问题