-
Notifications
You must be signed in to change notification settings - Fork 68
Thread Safety
Peasy was designed to be thread safe, so that you can safely execute many commands via threads without worrying about race conditions over resources.
There will be many times when you want to perform many updates against a data store all at once. For example, let's take a scenario where a user is making modifications to a grid, and modifying its underlying bound objects. Further, assume that all updates are performed once the user clicks a save button.
In a typical scenario, the application might loop through each object that is dirty and perform an update on it, in a synchronous manner. This can take alot of time, and can be advantageous to spawn threads (or System.Threading.Task
) to speed up this operation.
Here's an example that illustrates this scenario:
var categories = new System.Collections.Concurrent.ConcurrentDictionary<long, Category>();
var ids = new long[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Parallel.ForEach(ids, id =>
{
categories[id] = _categoriesService.GetByIDCommand(id).Execute().Value;
});
categories.ForEach(c => c.Value.LastModifiedDatetime = DateTime.Now);
Parallel.ForEach(categories.Values, category =>
{
categories[category.ID] = _categoriesService.UpdateCommand(category).Execute().Value;
});
In this example, we load all categories by ID that are specified in the ids
array. We do this by invoking the commands returned by GetByIDCommand
within the Parallel.ForEach method for each id in the array. This can speed up the time it takes to load all of the categories.
We then modify the LastModifiedDatetime
property on each object. Finally, to speed up the updating operations, we invoke the commands returned by UpdateCommand
within the Parallel.ForEach method.
In this scenario, we have exponentially (potentially) decreased the time to load and update the category objects in a completely thread-safe manner.