question on ThreadStart

S

Su

Hello,

What happens if either the class name nor the instance variable is specified
while calling ThreadStart(), ie, just with the method name as below :

MyClass{

public void Connect()
{
Thread connThread = new Thread(new ThreadStart(connThreadRoutine));
}

private void connThreadRoutine()

{
//access few non-static variables of the current object, including
synchronization objects
//and database connection
}

}



In the above case does the control defaults to the "this" pointer's instance
method, so that the correct non static variables are updated, or can this be
ambigious if there are multiple instances of MyClass?



Thank you

Su
 
R

rader

Peter is right, your code can't be compiled.
When your call an instance method with a delegate, the object(or "this") is
always needed.
Your code should be like this:
Thread connThread = new Thread(new ThreadStart(this.connThreadRoutine));

Actually,"this" is setted to the construtor of ThreadStart as an "invisible
man", when you wrap an instance method. Jeffrey Richter has explaned how a
delegate works in book "CLR Via C#(2nd)". Refer to Chapter 15,please.

Peter Duniho said:
Hello,

What happens if either the class name nor the instance variable is
specified
while calling ThreadStart(), ie, just with the method name as below :

The same thing as if you'd used the method name in any other context. For
an instance method, there _must_ be an instance, and without an explicit
reference, the instance must always be "this".
[...]
In the above case does the control defaults to the "this" pointer's
instance
method, so that the correct non static variables are updated, or can
this be
ambigious if there are multiple instances of MyClass?

It cannot be ambiguous. Note, however, that this is specific to C#.
VB.NET has an idea of a "default instance", which is what you get if you
try to use an instance member without an instance reference. The outcome
is still not ambiguous in that case (i.e. it doesn't pick the instance
randomly), but it's not as immediately obvious (C# code like that wouldn't
even compile).

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top