I have seen a few ways to do multithreading, and after reading a few posts on here I'm still unsure of what is the "correct" way to do multithreading. Specifically, I'm concerned with threads that will be monitoring inputs by constantly reading them and updating some output (like a brightness meter).
Way 1 is to have a thread and have a while (true) loop in there with a Thread.Sleep(1) and the polling code. I have noticed that if I don't put a Thread.Sleep(1) in there, the debugger stops responding and there's no way to get Visual Studio to attach to the debugger without erasing the current program. (My guess is that the main CLR thread doesn't get enough time to both interrupt VS while it's waiting for the CLR debugger and receive the attach message from VS. But if we put Thread.Sleep(1) in the polling thread, the main CLR thread would get a lot more time to run while the polling thread is sleeping and is able to interrupt VS and also receive the attach message (or debugging symbols).)
Way 2 is from http://forums.netdui...ring-whileloop/. One of the responses was as follows:
[color=rgb(164,164,164);font-family:helvetica, arial, sans-serif;]Posted [/color]21 February 2013 - 09:18 AM
Hi Ties,
The way that threads work in NETMF is that each thread gets up to ~10ms to execute before the thread scheduler pulls the execution to another thread. In order to make sure that interrupts are fired in sequence, NETMF queues and timestamps them...and then fires them off in order.
In multi-threaded and interrupt-driven apps, we generally avoid loops or any action that ties up the processor for long periods of time. But if you'd like to run long loops for threads, you'll probably want to create a thread and launch it there. With the newer versions of .NET MF, you can even use anonymous methods to launch code on another thread "in-line" in your code.
You can also create background threads for each of your tasks and then have them wait on an AutoResetEvent waithandle. Then when your interrupt gets fired, just Set the waithandle and your background thread will come to life. This also helps keep thread count down and prevent unintentional re-entry.
There are a massive number of powertools available in the C# language and NETMF, so there should be one that's great for the application at hand. We're happy to help guide the selection process.
Chris
My question is what does "background threads" mean in the context of this message? I cannot find the class BackgroundThread in NETMF, so was wondering if setting the priority of the thread to BelowNormal or Lowest makes it a background thread? Would a background thread also require a Thread.Sleep(1) in its while loop? (Side question: How do you create a thread "in-line", as mentioned in the quote above?)
Those are the two ways that I'm aware of. I'd love to hear more suggestions, and also thoughts about which threading methods are suited for what applications (polling an input, blinking an LED, etc.)