views:

55

answers:

1

I am trying to schedule a unit of work to process in the background, and produce a result. Originally I was thinking about extending the Task class, and scheduling that instance of the custom task. (thinking of Future and Runnable from Java) Each task encapsulates would multiple properties for input/output. Multiple tasks are processed simultaneous, and are completely autonomous.

However, I can't find any examples of doing so, so I am beginning to doubt that that is the correct way to go. Can someone provide the example of doing this correctly with the System.Threading.Tasks

+1  A: 

You do not need to subclass Task. Just instantiate a Task object and give it the method to be executed in the constructor.

The following example computes a value and stores it in a field along with a flag to indicate that the action is complete:

    int _taskResult;
    bool _taskFinished;

    /// <summary>Starts a background task to compute a value and returns immediately.</summary>
    void BeginTask()
    {
        _taskFinished = false;
        Task task = new Task(() =>
        {
            var result = LongComputation();
            lock (this)
            {
                _taskResult = result;
                _taskFinished = true;
            }
        });
        task.Start();
    }

    /// <summary>Performs the long computation. Called from within <see cref="BeginTask"/>.</summary>
    int LongComputation()
    {
        // Insert long computation code here
        return 47;
    }

Of course, in your other code that retrieves the result, you’d have to lock on the same object before checking _taskFinished and _taskResult.

Timwi
This is not as clean as I was hoping, as the result is shared. Considering the code for the computation is complex, it would have to exist in external Task_Like anyway.
Timur Fanshteyn
You can store the result any way you want. Your question asked how to use Tasks, and I think I demonstrated that. Of course, you can always ask a separate question if you need further help with something.
Timwi