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.
Related
I am a beginner on C#. There is a project I am working on need to use 2 threads. The main one is for displaying the usual Wpf pages. Another one monitoring the inputs from hardware. If there is a desired input signal detected, the whole system should stop and shows a warning page on the window, which is controlled by the main thread.
Now I get stuck on how to do the deal with the threads when the input signal detected. Should I pass a signal to the main thread, and ask the main thread to display the warning page, and stop the secondary thread. Or I should let the secondary thread display the warning page directly, and take over the control priority from the main thread?
Or I should let the secondary thread display the warning page directly, and take over the control from the main thread?
That makes literally no sense at all.
Should I stop the secondary thread and pass a signal to the main thread, and ask the main thread to display the warning page.
That also makes no sense at all, but at least there's a gleam of sort of what you mean here. To be absolutely clear, there's no such thing as "stopping threads" as you mean.
But yes, you send a message to the GUI thread to update its state, specifically using Dispatcher.BeginInvoke in WPF.
WPF, like most GUI toolkits on Windows at least, has sticky controls - which essentially means they have thread affinity and cannot be accessed from other thread which didn't create them. [You can verify that from source, there are calls to VerifyAccess() littered all over the place.]
That design constraint rules out the possibility of other thread "taking over" anything from another thread, ever.
But the world doesn't end there, and cross-thread communication is common enough requirement that the designers have provided you with the means to satisfy the same thread requirements yet send messages across threads.
The way to do that lies with two members of Dispatcher object each WPF window has. You can read the full details here and on associated pages for that type, but roughly it goes like
protected void Button_Clicked(object sender, EventArgs args) =>
Dispatcher.Invoke(() => { /* Your method body which will be executed on the proper thread. */ });
If you prefer asynchronous communication, you can use either BeginInvoke or InvokeAsync instead.
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 know there are other questions around this but most end up with the answer don't do what I am about to suggest. So I know you aren't supposed to. The reason for this question is I want to do it anyway, how can I do it...
Here is why I want to break the rules...
Let's say I have a complicated application, it's version 1 and we want our customers to submit errors to us in the event of crashes or hangs. Let's now say I have a button on the top of the main form they click to submit reports.
Let's now imagine that the application hung because of a deadlock...
It would be nice if that small piece of UI and a handler for that button could live on a thread other than the main ui thread so that it isn't caught up in the deadlock. When clicked it would gather all the call stacks for the other threads and submit them to our error reporting service.
Now, knowing the scenario, can this be done in .net?
Yes, there is no magic in creating UI on another thread than the "main thread". The important rule to always keep in mind is to interact with that UI on the thread that created it.
Still, I feel that you are attacking this from the wrong angle. You should probably instead make an effort to push all work off the main thread. That way you minimize the risk for that thread to freeze, and then you don't need to resort to unorthodox solutions for the error reporting.
I have various cases of creating forms on non-main thread, and it works fine every time.
Create a new Thread, and show a Form from it. New message loop will be created for that thread and everything will run fine.
What magic will you use to gather data from the crashed app and locked main thread, that's up to you :)
if application hung, your main message loop is dead, thus ui will not work. As workaround for your problem i'd consider usage of external application (another exe) which will be invoked in case of report
in any case, if you want to invoke UI from other thread you should perform context switch In case of winforms, follow this answer
It sounds like you'd like to keep the UI alive, even when some other operation is mired in a deadlock. If so, perhaps Asynchronous Programming would be of use. Using Async to manage a potentially hung up task would allow the remainder of the application to remain responsive.
we want our customers to submit errors to us in the event of crashes or hangs
You might also consider adding some degree if instrumentation/reporting, so that you'll have this data without requiring user input.
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.