Executing in Isolation

Isolation solves the shared data problem by giving everyone their own piece of data. You don't need to share if everyone at the party gets their own cake.

We can provide a Task with isolated data by using the constructor overload that takes a state object, as described in Chapter 2. Listing 3-3 updates our simple bank account example to use isolation. Each Task is given the current balance as a state object when it is created. The data is isolated because each Task only modifies its own version of the balance. When all of the Tasks have completed, we read the results and combine them to accurately update the bank account.

Listing 3-3. Isolation by Convention using System;

using System.Threading.Tasks;

namespace Listing_03 {

class BankAccount {

public int Balance { get; set;

class Listing_03 {

static void Main(string[] args) {

// create the bank account instance BankAccount account = new BankAccount();

// create an array of tasks Task<int>[] tasks = new Task<int>[l0];

for (int i = 0; i < 10; i++) { // create a new task tasks[i] = new Task<int>((stateObject) => {

0 0

Post a comment