[英]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:在 C# 中,线程是通过传递成员 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.这里
ThreadFunction()
不是 static,所以我猜 object 引用被传递给Thread
构造函数。
How can code inside ThreadFunction()
get to myObject
? ThreadFunction()
中的代码如何到达myObject
? Do I just use this
reference for that?我只是使用
this
参考吗?
In the exact example you give, simply by accessing this
.在您给出的确切示例中,只需访问
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.这允许您将任何类型的参数(此处为
string
)传递给线程 function。 If you need more than one, then you can always pass in a Tuple
or an object[]
or any other container of values.如果你需要多个,那么你总是可以传入一个
Tuple
或一个object[]
或任何其他值的容器。
If you go this way, you might want to make ThreadFunction
static
(this will lose you the option of using this
) as well.如果您以这种方式使用 go,您可能还需要制作
ThreadFunction
static
(这将使您失去使用this
的选项)。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.