I have an application that has a main UI and two modeless windows that run on the their own separate thread. When passing an object from thread to thread I just make a copy of of the object running on the main thread on the secondary thread. When I want to update the object itself and have that changed perpetuated down through the code and to the secondary thread how do I make this happen??? The secondary thread always keeps a copy of the old object and never updates unless the thread is killed or stopped and then spawned again.
There are a number of ways to tackle this. One would be a thread-safe shared instance of a repository for the object. When one thread updates it, the others would get an updated copy. You could use WCF to make this easy. See this article on WCF and concurrency for some ideas. This is an implementation of #Eric J's comment to your question.
Another would be to coordinate the threads via events. When one thread updates the object, an event is sent to the others. If the object doesn't change that often, it may be enough.
This question talks about a third possibility: BackgroundWorker.
Related
I'm building a WPF application. I'm doing some async communication with the server side, and I use event aggregation with Prism on the client. Both these things results in new threads to be spawned which are not the UI thread. If I attempt to do "WPF operations" on these callback and event handler threads the world will fall apart, which it now has started doing.
First I met problems trying to create some WPF objects in the callback from server. I was told that the thread needed to run in STA mode. Now I'm trying to update some UI data in a Prism event handler, and I'm told that:
The caller cannot access this thread because a different thread owns it.
So; what's the key to getting things right in WPF? I've read up on the WPF Dispatcher in this MSDN post. I'm starting to get it, but I'm no wizard yet.
Is the key to always use Dispatcher.Invoke when I need to run something which I'm not sure will be called on the UI thread?
Does it matter if it actually was called on the UI thread, and I do Dispatcher.Invoke anyway?
Dispatcher.Invoke = synchronously. Dispathcher.BeginInvoke = async?
Will Dispatcher.Invoke request the UI thread, and then stop to wait for it? Is it bad practice and risk of less responsive programs?
How do I get the dispatcher anyway? Will Dispatcher.CurrentDispatcher always give me the dispatcher representing the UI thread?
Will there exist more than one Dispatcher, or is "Dispatcher" basically the same as the UI thread for the application?
And what's the deal with the BackgroundWorker? When do I use this instead? I assume this is always async?
Will everything that runs on the UI thread (by being Invoked) be run in STA apartment mode? I.e. if I have something that requires to be run in STA mode - will Dispatcher.Invoke be sufficient?
Anyone wanna clearify things for me? Any related recommendations, etc? Thanks!
Going over each of your questions, one by one:
Not quite; you should only invoke onto the UI thread when necessary. See #2.
Yes, it does matter. You should not just automatically Invoke everything. The key is to only invoke onto the UI thread if necessary. To do this, you can use the Dispatcher.CheckAccess method.
That is correct.
Also correct, and yes, you do run the risk of less responsive programs. Most of the time, you are not going to be looking at a severe performance hit (we're talking about milliseconds for a context switch), but you should only Invoke if necessary. That being said, at some points it is unavoidable, so no, I would not say it is bad practice at all. It is just one solution to a problem that you will encounter every now and then.
In every case I have seen, I have made due with Dispatcher.CurrentDispatcher. For complex scenarios, this may not be sufficient, but I (personally) have not seen them.
Not entirely correct, but this line of thinking will not do any harm. Let me put it this way: the Dispatcher can be used to gain access to the UI thread for the application. But it is not in and of itself the UI thread.
BackgroundWorker is generally used when you have a time-consuming operation and want to maintain a responsive UI while running that operation in the background. Normally you do not use BackgroundWorker instead of Invoke, rather, you use BackgroundWorker in conjunction with Invoke. That is, if you need to update some UI object in your BackgroundWorker, you can Invoke onto the UI thread, perform the update, and then return to the original operation.
Yes. The UI thread of a WPF application, by definition, must be running in a single-threaded apartment.
There's a lot to be said about BackgroundWorker, I'm sure many questions are already devoted to it, so I won't go into too much depth. If you're curious, check out the MSDN page for BackgroundWorker class.
So i have 4 objects. Each one of them must execute up to 5 operations simultaneously and also all 4 object must be operated simultaneously. I created one thread for each object and inside 5 new threads ? I saw that after a period the threads are not executed anymore.
The question is : Is it ok to have thread in thread? or it's better to create a thread pool and run them in concurrency?
There is no such thing as "thread in a thread". Thread is entity that is global in whole process. It doesn't matter if it is created in one of other thread. The moment it is created, it becomes global and unrelated to thread it created it.
More about creating threads, you should be worried about access to shared resources and possible race conditions which might be much harder to track when threads are created in different places.
And from you description, I would recommend you to look at Task Parallel Library, which makes problems like this breeze.
It's ok. You actually need to do that sometimes, like when you're working with servers, you can create thread for each connected client from thread where you are listening for clients.
I am using Unity3D and Mono to make a multiplayer online game. The language is C# script. I know that Unity is not thread safe. C# in Mono allows you to create a new thread using System.Threading. But Unity would forbid the new thread from modifying any of the GameObjects.
In my code I started a new thread to wait for a callback from some of my native C code (incorporated into Unity as Plugins). In this way, when the callback gets called it will be on the new thread, not Unity's main thread which has the authority to manipulate GameObjects. However, I want the GameObjects to be modified. What should I do? Should I use the main thread to poll the new thread? Or is there any better solution?
There is more than one way to signal a main thread that data is available on a 2nd thread. Generally speaking, the first way might be to have the first thread "block" (wait) until the 2nd thread "signals"; however, without going into detail here this is not the approach you want to take, because blocking the main thread while you perform lengthy computations on your 2nd thread will make your game unresponsive at worst or jittery at best.
So this leaves the other approach which you brought up: polling. However often you feel necessary (once per frame, once every 60 frames), your main thread code (e.g. in a MonoBehaviour) will want to check on the status of the task in the 2nd thread. This could be via calling a method or checking a boolean value on an object "owned" by the 2nd thread. Via this approach, your task will indicate to the main thread polling whether things are "done" or "not done". Unity co-routines might be a useful mechanism for implementing your polling logic from the main thread.
However, you are not necessarily done yet. If your 2nd thread is going to repeatedly generate new data into the same variable or buffer, you have to also make sure your main thread will not read from a buffer that is being written by your 2nd thread to at the same time. For small amounts of data, you can use a double-buffering approach (two buffers/variables, one for reading, one for writing, which are swapped via pointer/reference exchange) when new data is ready; or you can use C# locks (but this can block your main thread with the side-effects described earlier).
Once your main thread has the data it needs, you can then of course proceed to modify your game objects from the main thread.
Note that your question is not all that specific to Unity. Most UI frameworks have this limitation (with good reason), and communication between threads is solved in similar ways in each instance.
I have a highly multithreaded application , where threads are started from multiple places and i would like to know if i can hook into the running process and just get alerted whenever a new Managed Thread is spawned. I should be able to get the following information
The parent thread
New thread
the method from which the new thread is started like <className>.<methodName>
The application is in C# 3.5
As far as I know there is no way to detect when a thread starts. The best solution is probably not to create thread directly, but instead do it via a "thread manager" class that will raise an event when it starts a thread.
State should be handle within the thread processing logic.
I suggest you create a wrapper class which wraps the thread logic and reports it's status and other items as needed. I created such a class for a multi-threaded application where I could corral the status of the threads and pipe that information to the GUI in a standardized way.
Of course I had the luxury of designing it up front, to which, you may not have.
I have an XNA application, and I need to redirect the input queue into a custom thread, instead of having it available only in the main thread. Is there an alternative to AttachThreadInput?
I did some searching on this, and I don't think you're going to find a great way to solve this. This post indicates that it may be possible if you "make a new input class, register those events in my games main thread, then start the thread to begin polling."
The general consensus from these two threads (including the one you started on the XNA forums) indicates to me that trying to send keyboard input to a different thread probably isn't the best idea, and that, if possible, the main thread should just handle the keyboard input and the other thread can read the input from the main thread's shared storage. An alternative would be the main thread telling the secondary thread to do certain functions based on what input it received.
Keyboard access from other thread
Keyboard Input on Another Thread
I'm not quite sure what you're asking, but I'll try to answer.
If you're trying to create a multi-player game and want input for each player to be handled by a thread you have to do the following:
Create the XNA objects related to Keyboard/Mouse/Gamepads in the main
execution thread of your
application
Pass the objects by reference to your custom input handling thread.
Threads share memory with the processes that spawn them, so any changes made to the object from inside your custom thread will be automatically accessible outside the thread by using your referenced object.
Hope this helps.