can an instance method be thread safe

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

If an instance method does not alter the containing class or any arguments of
a referenced type is it thread safe?

public void GetSomething() {
return new Something(this.Name);
}
public string Name;

Thanks,

Mike
 
Mike,

Not completely. Since you are accessing this.Name, that needs to be
thread safe. If access to this.Name is thread safe, then in this case, yes,
this is thread safe.

Hope this helps.
 
Nicholas,

In this case this.Name is:

public string Name { get { return this._name; } }
private string _name;

Which I believe is thread safe.

What would be a simple example of a property that is NOT thread safe?

Thanks,

Mike
 
miked said:
In this case this.Name is:

public string Name { get { return this._name; } }
private string _name;

Which I believe is thread safe.

What would be a simple example of a property that is NOT thread safe?

That's actually not thread-safe. It's possible that another thread will
change the value of _name, and you won't "see" the change until a
memory barrier occurs. This is possible even if _name is set in the
constructor. Now, in practice that kind of thing is unlikely, but if
you're trying to be "belt and braces" thread-safe you need to think
about things like that.

See
http://www.pobox.com/~skeet/csharp/threads/volatility.shtml for more on
the weird and wacky world of the memory model.
 
Is an accessor which locks on 'this' thread safe?

e.g.,

public string Name
{
get
{
lock (this) { return this._name; }
}
set
{
lock (this) { this._name = value; }
}
}
 
Dan Manges said:
Is an accessor which locks on 'this' thread safe?

e.g.,

public string Name
{
get
{
lock (this) { return this._name; }
}
set
{
lock (this) { this._name = value; }
}
}

Yes. Personally I don't like locking on "this" as it means you've
effectively made the lock available to anyone who has a reference to
your object. I prefer locking on private references.

See http://www.pobox.com/~skeet/csharp/threads/lockchoice.shtml
 
If something is read-only (set only by constructor) then it is thread safe.
If it is read-write by 2+ threads, then you need sync protection.
In this case, it looks like a read-only field and property so that would be
thread safe (if you don't modify _name anywhere else).

--
William Stacey [MVP]

| Nicholas,
|
| In this case this.Name is:
|
| public string Name { get { return this._name; } }
| private string _name;
|
| Which I believe is thread safe.
|
| What would be a simple example of a property that is NOT thread safe?
|
| Thanks,
|
| Mike
 

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

Back
Top