How do I get from C# thread to the object which member function was the parameter to that thread?
In C# threads are created by passing a member function:
class SomeClass {
public void ThreadFunction() {Thread.Sleep( Infinite ); }
};
SomeClass myObject = new SomeClass();
Thread thread = new Thread( myObject.ThreadFunction );
thread.Start();
Here ThreadFunction()
is not static, so I guess the object reference is passed to Thread
constructor.
How can code inside ThreadFunction()
get to myObject
? Do I just use this
refere开发者_高级运维nce for that?
Like this:
class SomeClass {
public void ThreadFunction(Object obj)
{
SomeClass myObject = (SomeClass)obj;
Thread.Sleep( Infinite );
}
};
SomeClass myObject = new SomeClass();
Thread thread = new Thread(new ParameterizedThreadStart(myObject.ThreadFunction) );
thread.Start(myObject)
In the exact example you give, simply by accessing this
.
In the general case, you can also do something like
class SomeClass {
public void ThreadFunction(object param)
{
var justAnExample = (string)param;
}
};
SomeClass myObject = new SomeClass();
Thread thread = new Thread(myObject.ThreadFunction);
thread.Start("parameter");
This allows you to pass a parameter of any type (here, a string
) to the thread function. If you need more than one, then you can always pass in a Tuple
or an object[]
or any other container of values.
If you go this way, you might want to make ThreadFunction
static
(this will lose you the option of using this
) as well.
精彩评论