当通过 webbrowser 控件构造时,我在 C# 中的对象将调用一些 JavaScript。然后,JavaScript 将成功或失败地回调我们的 c# 代码。我需要让 C# 对象的构造函数等到 JavaScript 返回回调后再离开构造函数。我该怎么做呢?
本质上,我需要确保对象在创建时始终正确初始化。这取决于 javascript 回调,这至少略有不同。
当通过 webbrowser 控件构造时,我在 C# 中的对象将调用一些 JavaScript。然后,JavaScript 将成功或失败地回调我们的 c# 代码。我需要让 C# 对象的构造函数等到 JavaScript 返回回调后再离开构造函数。我该怎么做呢?
本质上,我需要确保对象在创建时始终正确初始化。这取决于 javascript 回调,这至少略有不同。
Instead of having an async constructor (which is not possible with .NET, anyway (thanks Servy) (and I don't think any other framework that allows for that is a sane framework, if such a thing exists)), you should:
initialize()
method (name it like that or something similar).You could have a flag in each instance telling whether is has already passed through the post-Javascript initialization, and some logic in your class so that its instances can only be considered to be in a valid, ready, usable state after that initialization step. Good luck and happy coding :)