如何从构造函数调用异步方法? [英] How can I call async method from constructor?
问题描述
我需要从我的 Form1
构造函数中调用 async
方法.由于构造函数不能具有返回类型,因此无法添加 async void
.我阅读了
I need to call a async
method from my Form1
constructor. Since a constructor can't have a return type, I can't add a async void
. I read that static constructor can be async
but I need to call methods from constructor that aren't static
, such as InitializeComponent()
(since it's the Form's constructor).
班级是:
public partial class Form1 : Form
{
InitializeComponent();
//some stuff
await myMethod();
}
我也阅读了这但我仍然不知道如何实现(就我而言),因为该方法仍然需要使用 async
.
I read this one too but I still don't know how to implement this (in my case) since the method still requires to use async
.
推荐答案
不要在构造函数中执行此操作,而应在窗口的加载事件中执行此操作.您可以将已加载的事件处理程序标记为异步.
Don't do this in the constructor but in the loaded event of the window instead. You can mark the loaded eventhandler as async.
这篇关于如何从构造函数调用异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!