C# execute code on other thread

后端 未结 2 1230
清歌不尽
清歌不尽 2021-01-23 04:11

I have some trouble with threading in my application. I have a multi-threaded client/server application. I\'m also using C# MonoDevelop for Unity3d. Not sure if it makes any dif

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-23 04:13

    You could communicate with the original thread through a class such as

    class Communicator
    {
        public static volatile bool CreatePlayer;
    }
    

    And in socket code, change the CreatePlayer variable. In the reciever code, check the variable and create a player. After that, set CreatePlayer to false. Similarly with other things. Be careful about manipulating one variable across two threads at the same time - for example, it may be better to have four booleans for CreatePlayer than to have an int NumPlayersToCreate so that both threads aren't trying to constantly access the same data. Of course, you'd have to profile and see. One final thing: make sure the variables changed across both threads are marked as volatile. This makes each thread access the data from main memory rather than keeping it in cache (otherwise, each thread wouldn't notice the data being changed in the other thread's cache).

    Yes, this is not the most performant or elegant solution, but it is the simplest. I'm sure someone will suggest a something more involved; if you want, I can do that as well. However, you seem unfamiliar with multithreading, so I thought you'd want something straightforward to get started.

提交回复
热议问题