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

后端 未结 9 855
长发绾君心
长发绾君心 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:45

    Put a loop in your second thread, that sleeps most of the time, but every [Interval] it wakes up and checks a shared variable that tells it whether to run your method or not, and if that shared boolean is set to true, then it runs a method that performs whatever task you are trying to perform... In that method, have the method gather the data required from another shared variable.

    In main GUI thread, put the data into the method parameter shared variable, then set the boolean "Run" shared variable to true...

    Inside the worker method, remember to reset the shared bool "run" variable to false when you're done, so the loop won;t run the same instance over and over...

提交回复
热议问题