c# - 我想知道为什么我的处理函数同时运行它的所有函数而不是相互等待?
问题描述
我想知道为什么我的处理函数同时运行它的所有函数而不是相互等待?
有人能告诉我为什么我的处理程序同时执行 func1 和 func2 吗?
我的方法 1 和方法 2 完美运行,它们在等待前一个完成时执行。但是当它执行处理程序时。
但是 func1 和 func2 同时异步运行。我怎样才能解决这个问题?
public void Run()
{
lock (_theLock)
{
Task.Run(async () => {
await method1();
await method2();
await handler();
});
}
}
调用 func1 或 2 的处理程序方法:
private async Task handler() {
await _timer.func1();
await _timer.func2(); }
_timer 类:
public class _timer
public async void func1()
{
lock (lock)
{
test1();
}
}
public async void func2()
{
lock (lock)
{
test2();
}
}
public async Task test1()
{
await method1(); // the same method as in the run method
}
public async Task test2()
{
await method2(); // the same method as in the run method
}
public async Task method1()
{
var test1 = await GetDataFromSource1();
await doStuff(test1);
}
public async Task func2()
{
await method2(); // the same method as in the run method
}
public async Task method2()
{
var test2 = await GetDataFromSource2();
await doStuff(test2);
}
public async Task<List<items>> GetDataFromSource1() {
// retrieves data from database SQL
}
public async Task<List<items>> GetDataFromSource2() {
// retrieves data from database SQL
}
public async Task doStuff(List<string> items) {
// does stuff with the data
}
解决方案
问题1:async void
- 调用者无法知道它何时完成;使用async Task
orasync ValueTask
代替;你几乎不应该使用async void
.
问题 2:你await
在调用test1
or时没有test2
,所以......什么都没有等待
问题 3:你不能使用lock
with await
- 你需要使用不同的锁定原语,也许SemaphoreSlim(1,1)
(它像互斥锁一样工作)
obersvation:这些代码实际上都不是真正的异步
推荐阅读
- typescript - ReplicationTime 不能用于此版本的复制配置架构
- javascript - 使用 ImageMapType 的 getTileUrl 方法时如何去除 poi?
- java - Java Mail SMTP 身份验证要求检查而不发送邮件
- javascript - 单击按钮后刷新页面(确定/取消)
- html - 如何删除该文本框上的黑色边框?
- apache-pulsar - 无法获取分区元数据:授权失败
- sql - SQL 每个账户 ID 只返回 1 行
- html - 从 Shinymanager 中删除 html 元素
- jenkins - jenkins pod 找不到自己的本地程序
- .htaccess - 使用 .htaccess 使单词不区分大小写