如何暂停或恢复任务

问题描述:

我最近正在使用任务类,并且有关于暂停或恢复任务的问题。我们知道,当新任务启动时,还会创建相对线程,如何在运行过程中暂停或恢复任务?



例如:

I am using task class recently and there is a question about pausing or resuming a task.As we know,when new task starts,a relative thread is also created, how can I pause or resume the task during its running course?

For a example:

private void button1_Click(object sender, EventArgs e)
{
    Task task1 = Task.Factory.StartNew(needMuchTimeWork);
}

public void needMuchTimeWork()
{
    //here is a work that need much time
}

private void button2_Click(object sender, EventArgs e)
{
    //here i want to pause task1,how to do it??
}

在button1点击处理程序中,Task变量是本地的处理程序方法。为了使您能够访问所述任务变量,您必须将其声明为类字段。



In the button1 click handler the Task variable is local to the handler method. In order for you to be able to access said Task variable you'd have to declare it as a class field.

// Make Task task1 a class level variable
Task task1 = null;

private void button1_Click(object sender, EventArgs e)
{
    // Here we access the class field task1
    task1 = Task.Factory.StartNew(needMuchTimeWork);
}

public void needMuchTimeWork()
{
    //here is a work that need much time
}

private void button2_Click(object sender, EventArgs e)
{
    // Here we call the Pause method or whatever it is called. I also postulate there
    // is a predicate that indicates wether a task is paused or not whith a signature:
    // bool IsPaused().
    if(task1 != null && !task1.IsPaused())
    {
        task1.Pause();
    }
}