1

当通过 webbrowser 控件构造时,我在 C# 中的对象将调用一些 JavaScript。然后,JavaScript 将成功或失败地回调我们的 c# 代码。我需要让 C# 对象的构造函数等到 JavaScript 返回回调后再离开构造函数。我该怎么做呢?

本质上,我需要确保对象在创建时始终正确初始化。这取决于 javascript 回调,这至少略有不同。

4

2 回答 2

0

虽然您不能async/await在构造函数中使用,但仍然可以进行异步 JavaScript 调用并等待其完成,具体取决于您在 JavaScript 中以及在从 JavaScript 到 C# 的回调中实际执行的操作。它是通过组织一个嵌套的消息循环来完成的,这里是一个采用这种方法的例子。请注意,这可能很危险,因为它可能导致代码重入。

也就是说,您仍然可以重构代码以使用async/awaitStephen Cleary 在他的博客条目中描述的方法之一。

于 2013-09-18T22:15:13.583 回答
-1

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:

  • Construct your object in such a way that you don't depend on that Javascript call;
  • Call whatever logic you need that will be done past .NET boundaries, and when the Javascript is done and responds...
  • ... Call some 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 :)

于 2013-09-18T18:53:19.957 回答