Overload the Thread class and add a property / event?
If "overload" actually means inheritance, then no. Thread sealed, so it cannot be inherited, which means that you cannot add any properties or events to it.
Another elegant solution?
Create a class that encapsulates the logic that will be executed by the thread. Add a property or event (or both) that you can use to get progress information.
public class Worker { private Thread m_Thread = new Thread(Run); public event EventHandler<ProgressEventArgs> Progress; public void Start() { m_Thread.Start(); } private void Run() { while (true) {
Update:
Let me explain why a memory barrier is needed in this situation. An obstacle prevents reading from moving before other instructions. The most likely optimization does not come from the CPU, but from the JIT compiler, which βraisesβ the reading of Progress outside the while . This movement gives the impression of "obsolete" readings. Here is a semi-realistic demonstration of the problem.
class Program { static event EventHandler Progress; static void Main(string[] args) { var thread = new Thread( () => { var local = GetEvent(); while (local == null) { local = GetEvent(); } }); thread.Start(); Thread.Sleep(1000); Progress += (s, a) => { Console.WriteLine("Progress"); }; thread.Join(); Console.WriteLine("Stopped"); Console.ReadLine(); } static EventHandler GetEvent() {
It is imperative that the Release build run without the vshost process. Any of them will disable the optimization, which will cause an error (I believe that this does not play in versions 1.0 and 1.1 due to their more primitive optimization). The error is that "Stopped" is never displayed, although it clearly should be. Now uncomment the Thread.MemoryBarrier call and notice the change in behavior. Also keep in mind that even the most subtle changes in the structure of this code currently impede the compiler's ability to do this optimization. One such change would actually be to call a delegate. In other words, you cannot currently reproduce the obsolete reading problem using a null check followed by a call pattern, but there is no CLI specification (which I know anyway), which prevents the future hypothetical JIT compiler from reusing this "lift ", optimization.
Brian gideon
source share