【发布时间】:2021-09-10 07:22:14
【问题描述】:
出于某种原因,尽管这个问题在我的谷歌搜索中出现了很多,但我似乎找不到真正的答案。也许我只是用错了代表,我不确定。如果是 X-Y 问题,我很高兴有其他处理方法。
说我有这个:
public class SomeLibrary
{
public delegate void OnSomethingHappened(EventInfo eventInfo);
public OnSomethingHappened onSomethingHappened;
public void SomeMethod()
{
// ...
// Something happened here, so we'd better trigger the event
onSomethingHappened?.Invoke(eventInfo);
// ...
}
}
public class MyCode
{
public void SomeInitialisationMethod()
{
SomeLibrary someLibrary = new SomeLibrary();
someLibrary.onSomethingHappened += SomeEventHandler;
}
private void SomeEventHandler(EventInfo eventInfo)
{
DoSyncProcessing(eventInfo);
}
}
应该没问题(除了愚蠢的错别字)。
现在想象一下,我的常规同步 DoSyncProcessing 函数突然变得异步,就像在这个神奇的非函数代码中一样:
public class SomeLibrary
{
public async delegate Task OnSomethingHappened(EventInfo eventInfo); // <<< IDK what I'm doing here!
public OnSomethingHappened onSomethingHappened;
public void SomeMethod()
{
// ...
// Something happened here, so we'd better trigger the event
await onSomethingHappened?.Invoke(eventInfo); // <<< IDK what I'm doing here either!
// ...
}
}
public class MyCode
{
public void SomeInitialisationMethod()
{
SomeLibrary someLibrary = new SomeLibrary();
someLibrary.onSomethingHappened += SomeEventHandler;
}
private async Task SomeEventHandler(EventInfo eventInfo)
{
await DoAsyncProcessing(eventInfo);
}
}
我该如何处理?这样做的正确方法是什么?
【问题讨论】:
-
编译器在这里给你一个非常强烈的提示:CS0106 "The modifier 'async' is not valid for this item" - 所以...只需删除
async修饰符? -
@MarcGravell 原来你是对的,我只是以某种方式搞砸了我的测试。我的意思是我知道
async在那种情况下是无效的,但似乎我不能await委托调用无论出于何种原因。没关系,毕竟它确实有效。
标签: c# asynchronous async-await delegates