Answer the question
In order to leave comments, you need to log in
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)
{
//?
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question