我正在尝试理解C#中的异步编程。我创建了一个示例函数,可以仅调用一次。例如读取大文件。我想创建一个查询,并在查询中等待请求,直到它们可以安全地读取文件。
AsyncWork aw = new AsyncWork();
Task.Run(() => {
for (int count = 0; count < 10; count++) {
aw.DoAsyncWork(count);
Console.WriteLine("request added");
}
});
Console.ReadKey();
以及AsyncWork
public class AsyncWork {
int Requests = 0;
int Workers = 0;
public AsyncWork() { }
public async Task DoAsyncWork(int count) {
Requests++;
while (Workers > 0) ;
Workers++;
Requests--;
if (Workers > 1) Console.WriteLine("MORE WORKERS AT ONCE");
Console.WriteLine(count.ToString() + " Started task");
//reading from file
await Task.Delay(1000);
Console.WriteLine(count.ToString() + " Ended task");
Workers--;
}
}
我原本期望有10个请求,然后逐个完成。但实际输出的情况是:
0 Started task
request added
0 Ended task
1 Started task
request added
1 Ended task
2 Started task
request added
2 Ended task
3 Started task
request added
3 Ended task
4 Started task
request added
4 Ended task
5 Started task
request added
5 Ended task
6 Started task
request added
6 Ended task
7 Started task
request added
7 Ended task
8 Started task
request added
8 Ended task
9 Started task
request added
9 Ended task
为什么它在同步运行?
DoAsyncWork
是异步执行的,但是在任务中有一个循环,每次该方法都会执行,那么你期望发生什么? - Markiian Benovskyiasync
,并且你没有使用await
来等待DoAsyncWork
的执行。 - Kenneth K.while (Workers > 0) ;
? - FCin