gpt4 book ai didi

c# - async partial void MyPartialMethod() 危险吗?

转载 作者:太空狗 更新时间:2023-10-30 00:30:17 27 4
gpt4 key购买 nike

我已经看到很多关于编写代码的警告,例如...

public async void MyDangerousMethodWhichCouldCrashMyApp...

我读到过 Eventhandlers 没问题,因为它们必须返回 void。然而partial methods还必须返回 void。你可以有以下代码......

static void Main(string[] args)
{
MainAsync().Wait();
Console.ReadLine();
}

async static Task MainAsync()
{
MyCodeGeneratedClass c = new MyCodeGeneratedClass();
try
{
await c.MyCodeGeneratedMethod();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}

public partial class MyCodeGeneratedClass
{
public async Task MyCodeGeneratedMethod()
{
HttpClient client = new HttpClient();
Console.WriteLine(await client.GetStringAsync("http://msdn.microsoft.com"));
MyCustomCode();
}

partial void MyCustomCode();
}

然后实现为...

partial class MyCodeGeneratedClass
{
async partial void MyCustomCode()
{
HttpClient client = new HttpClient();
Console.WriteLine(await client.GetStringAsync("http://msdn.microsoft.com"));
throw new Exception("Boom");
}
}

但是如果 MyCustomCode 的实现遇到异常,应用程序会发生什么情况呢?

如果不行,考虑到 async/await 的流行程度,这是否意味着分部方法基本上已经过时了?代码生成系统是否应该停止公开部分方法以支持事件,或者最好还是在基类中清空 protected 虚拟方法?即

protected virtual Task MyCustomCode(T foo)
{
return Task.FromResult(0);
}

编辑:好的,所以我对代码进行了多次更新。在我写的原始伪代码没有得到好评之后。我认为上面的代码表明 async partial void MyPartialMethod 肯定存在问题,因为对 MyCodeGeneratedMethod 的调用似乎确实降低了应用程序域,尽管围绕调用进行了 try catch。我只是想知道是否有比转移到 protected 虚拟基类方法更好的选择。

最佳答案

But what will happen to the application if the implementation of MyCustomCode encounters an exception?

async void 方法的语义是直接在方法开始时的当前 SynchronizationContext 上引发异常。关于 async void 的这个和其他有趣的事实在我的 async best practices 中有所介绍。文章。

does that mean partial methods are essentially obsolete?

与事件处理程序一样过时。所以,不,不是真的。但是,它们并未更新为允许 Task 的返回类型,因此它们似乎是一种语言功能,并未随语言的其余部分积极更新。

Should code generation systems stop exposing partial methods in favour of events or perhaps better still empty protected virtual methods in a base class?

事件根本不会改变这一点;它们仍将使用 async void 实现。

如果“钩子(Hook)”需要是异步的,那么这会改变所有生成的代码,因为它也必须都是异步的。

仅当生成的代码需要来自该部分方法的某些结果时,异步部分方法才会起作用并且实现必须执行一些异步工作才能生成该结果。根据我的经验,部分方法在概念上更像是事件,因此 async void 是可以接受的。

关于c# - async partial void MyPartialMethod() 危险吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39362143/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com