我知道这是一个老问题,但我想提供一个例子,说明如何创造性地使用yield关键字。我真的从这个技巧中受益良多。希望这将有助于任何人谁偶然遇到这个问题。
注意:不要认为yield关键字仅仅是构建集合的另一种方式。收益率的很大一部分力量来自于这样一个事实,即在执行过程中暂停
方法或属性,直到调用代码遍历下一个值。以下是我的例子:
使用yield关键字(与Rob Eisenburg的Caliburn一起使用)。微协程实现)允许我像这样表达对web服务的异步调用:
public IEnumerable<IResult> HandleButtonClick() {
yield return Show.Busy();
var loginCall = new LoginResult(wsClient, Username, Password);
yield return loginCall;
this.IsLoggedIn = loginCall.Success;
yield return Show.NotBusy();
}
这将做的是打开我的BusyIndicator,在我的web服务上调用Login方法,将我的IsLoggedIn标志设置为返回值,然后关闭BusyIndicator。
Here's how this works: IResult has an Execute method and a Completed event. Caliburn.Micro grabs the IEnumerator from the call to HandleButtonClick() and passes it into a Coroutine.BeginExecute method. The BeginExecute method starts iterating through the IResults. When the first IResult is returned, execution is paused inside HandleButtonClick(), and BeginExecute() attaches an event handler to the Completed event and calls Execute(). IResult.Execute() can perform either a synchronous or an asynchronous task and fires the Completed event when it's done.
LoginResult看起来像这样:
public LoginResult : IResult {
// Constructor to set private members...
public void Execute(ActionExecutionContext context) {
wsClient.LoginCompleted += (sender, e) => {
this.Success = e.Result;
Completed(this, new ResultCompletionEventArgs());
};
wsClient.Login(username, password);
}
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
public bool Success { get; private set; }
}
它可能有助于设置类似这样的东西,并逐步执行以观察发生了什么。
希望这能帮助到一些人!我真的很喜欢探索不同的收益使用方式。