在C#4.0中继承Task类 [英] Inheriting Task class in C# 4.0

查看:307
本文介绍了在C#4.0中继承Task类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试安排一个工作单元在后台处理,并产生结果。最初,我正在考虑扩展Task类,并计划该自定义任务的实例。 (从Java来思考Future和Runnable)每个任务都将封装多个属性以用于输入/输出。多个任务同时处理,并且完全是自主的。

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.

但是,我找不到这样做的任何示例,因此我开始怀疑那是正确的要走的路。有人可以提供使用System.Threading.Tasks

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

推荐答案

正确执行此操作的示例吗?您不需要子类任务。只需实例化 Task 对象,并为其提供要在构造函数中执行的方法。

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;
    }

当然,在其他检索结果的代码中,在检查 _taskFinished _taskResult 之前锁定同一对象。

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

这篇关于在C#4.0中继承Task类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆