我对async/await编程很新,有时我觉得我理解它,然后突然发生了一些事情,并引发了我的循环.
我在测试winforms应用程序中尝试这个,这是我的一个版本的片段.这样做会阻止UI
private async void button1_Click(object sender, EventArgs e)
{
int d = await DoStuffAsync(c);
Console.WriteLine(d);
}
private async Task<int> DoStuffAsync(CancellationTokenSource c)
{
int ret = 0;
// I wanted to simulator a long running process this way
// instead of doing Task.Delay
for (int i = 0; i < 500000000; i++)
{
ret += i;
if (i % 100000 == 0)
Console.WriteLine(i);
if (c.IsCancellationRequested)
{
return ret;
}
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
现在,当我通过在Task.Run中包装"DoStuffAsync()"的主体进行轻微更改时,它的工作完全正常
private async Task<int> DoStuffAsync(CancellationTokenSource c)
{ …Run Code Online (Sandbox Code Playgroud) 我是 C# 和面向对象编程的新手。我一直在尝试在我的 GUI 中实现一个“取消”按钮,以便用户可以在过程中停止它。
我读过这个问题:如何实现停止/取消按钮?并确定 backgroundWorker 对我来说应该是一个不错的选择,但是给出的示例没有解释如何将参数传递给 backgroundWorker。
我的问题是我不知道如何将参数传递给 backgroundWorker 以使其停止进程;我只能让 backgroundWorker 停止自己。
我创建了以下代码来尝试了解这一点,其中我的表单有两个按钮(buttonStart 和 buttonStop)和一个 backgroundWorker(backgroundWorkerStopCheck):
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
using System.Timers;
namespace TestBackgroundWorker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Set the background worker to allow the user to stop the process.
backgroundWorkerStopCheck.WorkerSupportsCancellation = true;
}
private System.Timers.Timer myTimer;
private void backgroundWorkerStopCheck_DoWork(object sender, DoWorkEventArgs e)
{
//If cancellation is pending, cancel work.
if (backgroundWorkerStopCheck.CancellationPending)
{ …Run Code Online (Sandbox Code Playgroud) c# multithreading backgroundworker argument-passing cancel-button