K
K
kykyryky2016-09-30 18:14:07
.NET
kykyryky, 2016-09-30 18:14:07

How to correctly pause and continue the execution of a Task from another thread?

There is a form with 3 buttons: start, pause and continue, as well as a progress bar to display the task.
"I pause" with lock. Here is the code:

public class DataForProgress
    {
        public int Count { get; set; }
        public int Value { get; set; }
    }
    public partial class Form1 : Form
    {
        private object syncObj = new object();
        private static IProgress<DataForProgress> progress;
        public Form1()
        {
            InitializeComponent();
            progress = new Progress<DataForProgress>((i) =>
            {
                progressBar1.Maximum = i.Count;
                progressBar1.Value = i.Value;
            });
        }

        public Task LongRunningTask(IProgress<DataForProgress> progress)
        {
            return Task.Run(() =>
            {
                int count = 5;
                for (int i = 1; i <= count; i++)
                {
                    lock (syncObj) { }
                    progress.Report(new DataForProgress
                    {
                        Value = i,
                        Count = count
                    });
                    Thread.Sleep(2000);
                }
            });
        }

        public Task Pause(IProgress<DataForProgress> progress, int val, int count)
        {
            return Task.Run(() =>
            {
                lock (syncObj)
                {
                    progress.Report(new DataForProgress
                    {
                        Value = val,
                        Count = count
                    });
                    Thread.Sleep(10000);
                }
            });
        }

        private async void StartButton_Click(object sender, EventArgs e)
        {
            label1.Text = "Выполняется...";
            await LongRunningTask(progress);
            label1.Text = "Завершено";
        }

        private async void PauseButton_Click(object sender, EventArgs e)
        {
            label1.Text = "Пауза";
            await Pause(progress, progressBar1.Value, progressBar1.Maximum);
        }

        private void ContinueButton_Click(object sender, EventArgs e)
        {
            //?
        }
    }

How to continue the task?
Yes, and stopping the thread for n seconds using Thread.Sleep to simulate a pause, it seems to me not the best idea ... but the main task is to continue the execution of the task.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Iron Bug, 2016-09-30
@kykyryky

ManualResetEventSlim

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question