Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
C#
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??
}
Posted
Updated 15-Nov-11 23:51pm
v3
Comments
Slacker007 16-Nov-11 5:52am    
Edit: spelling and readability.

1 solution

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.

C#
// 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();
    }
}
 
Share this answer
 
Comments
wuxi_taihu 16-Nov-11 10:24am    
thanks to your answer firstly,but function Pause() is not a method of class task

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900