Does DataFlow Object need to be locked if same object used in different thread

52 views Asked by At

I am using the same dataflow objects in different threads. Do locks have to be used on the dataflow objects or are the objects automatically thread safe?
For example:

// Dataflow object defined
ITargetBlock<FileQueueItem> producerChange = new BufferBlock<FileQueueItem>();

TransformBlock<FileQueueItem, FileQueueItem> transformBlock = new TransformBlock<FileQueueItem, FileQueueItem>(
            f => 
            {/*...*/});

ActionBlock<FileQueueItem> actionBlock = new ActionBlock<FileQueueItem>(f=>
            {/*...*/});

// DataFlow objects linked
producerChange .LinkTo(transformBlock );
transformBlock .LinkTo(actionBlock);


// DataFlow object method where datadlow objects used in a thread
public async void OnRunDataFlow(FileQueueItem f)
{
    Task.Run(() =>
    {
        var sent = await producerChange.SendAsync(f);
    });
}
1

There are 1 answers

0
Theodor Zoulias On

No, the objects are not automatically thread-safe. In case your dataflow setup allows the same object to be used by more than one threads concurrently, you'll have to synchronize the access to the objects using the lock statement appropriately, otherwise the state of your objects might become corrupted.