I have another question about threadsaftey according to memory access.
What about the synchronisation of objects passed to BackgroundWorker RunWorkerAsync(object) and returning to Result?
Lets say we have class (simplified)
We assume that threads will not access the same objects at the same time.
public class WorkerArgs
{
// Do we have to sync this with lock, since bgWorker will access them?
public string FileName {get;}
public object Any {get;}
public WorkerArgs (string fileName, object any)
{
FileName = fileName;
Any = any;
}
}
...
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
WorkerArgs args = (WorkerArgs)e.Arguments
string fileName = args.FileName;
MemoryStream ms = new MemoryStream();
while ( ... )
{
.. args.Any ....
}
// Do we have to box ms and put lock arround?
e.Result = ms;
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
... = (MemoryStream)e.Result ;
}
So it is still not clear to me when to Lock or Fencing when simultaneous access of two or more threads at the same time is barred. But threads can accessing the same object afterwards.
Thank you very much !
A lock is only needed, when something is used by multiple things in parallel AND its content can be changed.
In your example the WorkArgs
are immutable (can only be changed by creating a new instance). In that case everything is fine. The background worker receives the args object and nobody is able to change its properties (they are read-only). Thus a lock is not needed.
Same is true for your result, cause while the value is settable within the DoWork()
method, the Completed()
callback gets a read-only property.
Depending on how often you call the DoWork()
callback and maybe the object Any
is something more specific that contains something that will be changed from the DoWork()
AND changed from outside while both methods are running, a lock could be needed.