【发布时间】:2013-10-15 03:35:03
【问题描述】:
我有一个视图模型,它是我的 Android 和 iOS 应用程序的 UDP 网络浏览器(由 Xamarin 提供支持)。 UDP 用于广播应用程序的活动实例并侦听广播以发现本地 (Wifi) 网络上的其他应用程序实例。
我的视图模型有属性
public AppInstanceList AppInstances
{
get; set;
}
还有一个方法
public async Task StartDiscoveringAppInstancesAsync()
它设置了一个while循环,通过UPD异步监听:
while(this.networkService != null)
{
var discoveredInstance = await this.networkService.DiscoverAppInstanceAsync ();
// Omitted: store the discovered instance and add to list of discovered instances.
this.AppInstances.Add(...);
// Wait a bit before checking again.
await Task.Delay(1000);
}
我对这个方法的问题是Task 的返回类型。显然,不应等待该方法 - 它是无限循环并一直运行直到发现停止。
所以我应该把它改成void吗?但这会违反 async/await 原则,其中 void 只能用于事件。
每当我遇到这样的话题时,我都会想知道我的实现是否真的是糟糕的设计,并且有一种不同且更简洁的方法。还是视图模型的用户不应该 await 方法的结果?
【问题讨论】:
标签: c# .net async-await