我需要通过发送一些参数来调用异步函数。不带参数也可以,但是我需要通过签名发送参数。
这是我的代码:
//这是我当前的代码,在没有参数的情况下运行。
private int Counting()
{
for (int i = 0; i < 2000; i++)
{
Console.WriteLine(i.ToString());
Thread.Sleep(5);
}
return 0;
}
private async void button2_Click(object sender, EventArgs e)
{
Task<int> task = new Task<int>(Counting);
task.Start();
MessageBox.Show("Job started ..");
int countValue = await task;
MessageBox.Show("Job Done");
}
//但我需要这样做:
private int Counting(int maxCount)
{
for (int i = 0; i < maxCount; i++)
{
Console.WriteLine(i.ToString());
Thread.Sleep(5);
}
return 0;
}
private async void button2_Click(object sender, EventArgs e)
{
Task<int> task = new Task<int>(Counting(2000));
task.Start();
MessageBox.Show("Job started ..");
int countValue = await task;
MessageBox.Show("Job Done");
}
我该怎么做?
最佳答案
您需要使用 lambda 语法
Task<int> task = new Task<int>(() => Counting(2000));
关于c# - 如何在异步函数中发送参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54017046/