C# 计算按下异步按钮的次数(或是否正在进行某些操作)
我知道对于异步操作,可以跟踪其进度,但稍后我会尝试。现在,我有了一个简单的窗口窗体,其中有一个按钮(或一对按钮,数字无关紧要)。这些按钮调用异步操作C# 计算按下异步按钮的次数(或是否正在进行某些操作),c#,async-await,C#,Async Await,我知道对于异步操作,可以跟踪其进度,但稍后我会尝试。现在,我有了一个简单的窗口窗体,其中有一个按钮(或一对按钮,数字无关紧要)。这些按钮调用异步操作 public async void Button1_Click(...) { await Button1_OperationAsync(...); } 如果我不按下按钮,什么都不会发生,但如果我按下按钮,则按钮1\u OperationAsync将启动(并等待)。(我不确定是否应该称之为“线程”) 但是如果我按两次按钮会发生什么?然后在第一
public async void Button1_Click(...)
{
await Button1_OperationAsync(...);
}
如果我不按下按钮,什么都不会发生,但如果我按下按钮,则按钮1\u OperationAsync
将启动(并等待)。(我不确定是否应该称之为“线程”)
但是如果我按两次按钮会发生什么?然后在第一个异步操作完成之前,再次调用按钮1\u OperationAsync
。(或者,如果按下另一个类似按钮,则调用按钮2\u OperationAsync
)
甚至第二个异步操作也可能在第一个异步操作之前完成
我想要的是一个简单的方法,知道是否有任何操作正在进行。所以我认为应该有一个变量,在调用一个操作时增加它,在一个操作完成时减少它。差不多
int numberOfOps=0;
public async void Button1_Click(...)
{ numberOfOps++;
textBox1.Text="Started!";
await Button1_OpeationAsync(...);
numberOfOps--;
if(numberOfOps<=0)
{
textBox1.Text="Done!";
}
}
int numberOfOps=0;
公共异步无效按钮1\u单击(…)
{numberOfOps++;
textBox1.Text=“开始!”;
等待按钮1_操作异步(…);
数字运算--;
如果(numberOfOps有一个任务数组和类级别的任务对象:
private List<Task> tasks = new List<Task>();
private Task task = null;
使用async
/await
时,除了UI线程外,您没有为UI代码使用任何线程。在按钮1\u OpeationAsync
方法中调用的代码可能使用单独的线程,但调用代码将保留在UI线程上
尝试使用以下代码进行游戏:
private int numberOfOps = 0;
private async void button1_Click(object sender, EventArgs e)
{
textBox1.Text = $"Started! {++numberOfOps}";
await Task.Delay(TimeSpan.FromSeconds(5.0));
textBox1.Text = $"Started! {--numberOfOps}";
if (numberOfOps == 0)
{
textBox1.Text = "Done!";
}
}
工作正常。您可以在多个按钮之间使用numberOfOps
变量
如果希望使代码易于重用,请尝试以下方法:
int numberOfOps = 0;
private async Task RunOp(Func<Task> op)
{
textBox1.Text = $"Started! {++numberOfOps}";
await op();
textBox1.Text = $"Started! {--numberOfOps}";
if (numberOfOps == 0)
{
textBox1.Text = "Done!";
}
}
private async void button1_Click(object sender, EventArgs e)
{
await this.RunOp(() => Button1_OpeationAsync(...));
}
private async void button2_Click(object sender, EventArgs e)
{
await this.RunOp(() => Button2_OpeationAsync(...));
}
int numberOfOps=0;
专用异步任务RunOp(Func op)
{
textBox1.Text=$“已启动!{++numberOfOps}”;
等待op();
textBox1.Text=$“已启动!{--numberOfOps}”;
如果(numberOfOps==0)
{
textBox1.Text=“完成!”;
}
}
私有异步无效按钮1\u单击(对象发送方,事件参数e)
{
等待此消息。RunOp(()=>按钮1\u操作异步(…);
}
私有异步无效按钮2\u单击(对象发送方,事件参数e)
{
等待此消息。RunOp(()=>按钮2\u操作异步(…);
}
int numberOfOps = 0;
private async Task RunOp(Func<Task> op)
{
textBox1.Text = $"Started! {++numberOfOps}";
await op();
textBox1.Text = $"Started! {--numberOfOps}";
if (numberOfOps == 0)
{
textBox1.Text = "Done!";
}
}
private async void button1_Click(object sender, EventArgs e)
{
await this.RunOp(() => Button1_OpeationAsync(...));
}
private async void button2_Click(object sender, EventArgs e)
{
await this.RunOp(() => Button2_OpeationAsync(...));
}