best solution to overcome threading issue on shared object

Viewed 210

Using Task Parallel Library in .net 4.0, I want to know what is the best solution to this situation :

My code is starting a task that do a lot of long running steps (steps need to be done one after other). I have an object Result that aggregate the result of each steps. The result object is modified in the task ( so in the thread related to this task ). I also have an web service where we can fetch the current Result object to see the progress of the task. So the Result object is a share object between the task and the main thread of my code. What is the best approach to implement this to be sure I don't have threading issues and things like that ?

Here a sample of what i'm talking about. Just note that _doWork would not be a static like in the code, it will be a member in another class higher in the hierarchy.

using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class Step1Result
    {
    }

    public class Step2Result
    {
    }

    public class Result
    {
        public Step1Result Step1Result;
        public Step2Result Step2Result;
    }

    class DoWork
    {
        public Result Result;

        public DoWork()
        {
            Result = new Result();
        }

        public void Process()
        {
            // Execute Step 1
            Result.Step1Result = Step1();
            Result.Step2Result = Step2();

            // Other Steps ( long - running )
        }

        public Step1Result Step1()
        {
            // Long running step that can takes minutes

            return new Step1Result();
        }

        public Step2Result Step2()
        {
            // Long running step that can takes minutes

            return new Step2Result();
        }
    }
    class Program
    {
        private static DoWork _doWork;

        static void Main(string[] args)
        {
            _doWork = new DoWork();

            var task = Task.Factory.StartNew(() => _doWork.Process());
            task.Wait();
        }

        // This method will be called from a web service at anytime.
        static Result CalledFromWebService()
        {
            return _doWork.Result;
        }
    }
}

The trouble here is accessing _doWork.Result from both the Task and the Main thread. True ? What could be done to overcome this ?

3 Answers
Related