如何暂停或恢复任务 [英] how to pause or resume a task

查看:95
本文介绍了如何暂停或恢复任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如:

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


这篇关于如何暂停或恢复任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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