Good question. First to think about: do you really need to? There is much better method: to wrap a thread and pass
this
. After that, the thread accesses anything in the class. Isn't that nice?
internal class ThreadWrapper {
internal ThreadWrapper() {
Thread = new System.Threading.Thread(Body);
}
internal void Start() { this.Thread.Start(); }
internal void Abort() { this.Thread.Abort(); }
void Body() {
if (this.SomeByRefParameter == null)
this.SomeByRefParameter = new System.Text.StringBuilder();
}
object SomeByRefParameter;
System.Threading.Thread Thread;
}
Can you see what's going on? We managed to run non-static (instance) method as a thread start point. As this is an instance method, Body has hidden parameter called this; it is used to pass an instance of the
ThreadWrapper
. As we have the instance, we can access any members of this instance (shown on example of
SomeByRefParameter
). You can have other methods of the wrapper accessible from outside and pass any parameter using by value of by reference methods. Don't forget to use synchronization primitives, such as
lock
.
Don't be afraid; this method of starting thread is not very well documented, but it is much more reliable than starting point with parameter because type casting is not required.
—SA