K
Kurt
Below is a class that can accessed from multiple threads and I want the class to be thread safe. I have a private timer member whose interval can be changed by different threads. Which is the correct way to define the property below.
Thanks
Kurt
Class1
{
private Timer _timer = new Timer();
// Example 1
// No lock since interval is a numeric value and does not require locking
public int TimerInterval
{
get
{
return this._timer.Interval;
}
set
{
this._timer.Interval = value;
}
}
// Example 2 Lock the _timer object only
public int TimerInterval
{
get
{
lock(this._timer)
return this._timer.Interval;
}
set
{
lock(this._timer)
this._timer.Interval = value;
}
}
// Example 3 lock the whole class
public int TimerInterval
{
get
{
lock(this)
return this._timer.Interval;
}
set
{
lock(this)
this._timer.Interval = value;
}
}
}
Thanks
Kurt
Class1
{
private Timer _timer = new Timer();
// Example 1
// No lock since interval is a numeric value and does not require locking
public int TimerInterval
{
get
{
return this._timer.Interval;
}
set
{
this._timer.Interval = value;
}
}
// Example 2 Lock the _timer object only
public int TimerInterval
{
get
{
lock(this._timer)
return this._timer.Interval;
}
set
{
lock(this._timer)
this._timer.Interval = value;
}
}
// Example 3 lock the whole class
public int TimerInterval
{
get
{
lock(this)
return this._timer.Interval;
}
set
{
lock(this)
this._timer.Interval = value;
}
}
}