我想通过单击“开始”按钮启动异步过程,并在必要时通过“取消”按钮取消它。
正如预期的那样,我已经在Start上启动了异步任务,但问题在于Await。 如何停止当前正在运行的异步任务?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
CancellationTokenSource cs = new CancellationTokenSource();
private void Start(object sender, EventArgs e)
{
operate();
}
private void CancelProcess(object sender, EventArgs e)
{
cs.Cancel();
}
public async Task operate()
{
await Task.Factory.StartNew(() => progres(cs.Token), cs.Token);
}
void progres(CancellationToken css)
{
string o1 = Thread.CurrentThread.ManagedThreadId.ToString();
for (int i=0; i<101; i++)
{
Thread.Sleep(100);
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke(
(Action)delegate
{
progressBar1.Value = i;
textBox1.Text = o1;
});
}
else
{
progressBar1.Value = i;
}
}
}
}