我有以下方法,希望有人可以帮助我;它使用MvvmCross IMvxLocationWatcher。基本上,这个想法是从封装观察者的方法中获取MvxGeoLocation结果。
protected internal static async Task<MvxGeoLocation> GetCurrentLocationAsync()
{
const int timeoutInMs = 5000;
return await Task.Factory.StartNew(() =>
{
MvxGeoLocation result = null;
// wait event
var manualResetEvent = new ManualResetEvent(false);
var locationWatcher = Mvx.Resolve<IMvxLocationWatcher>();
locationWatcher.Start(new MvxLocationOptions {Accuracy = MvxLocationAccuracy.Coarse},
// success
location =>
{
result = location;
manualResetEvent.Set();
},
// fail
error =>
{
result = null;
manualResetEvent.Set();
});
// all done
manualResetEvent.WaitOne(timeoutInMs);
locationWatcher.Stop();
return result;
});
}
该代码可以在WindowsPhone中正常工作。ResetEvent保存我从结果中设置的事件。
但是,在MonoTouch(iOS)中,我什么也没得到,并且重置事件超时(没有任何超时,它永远不会返回)。
通过将locationWatcher设置为全局类变量而不是停止它,我可以看到该方法存在后立即返回定位结果。
我想我可以尝试其他几件事;Thread.Sleep(我觉得很丑)和Locking(但我认为ResetEvent几乎以相同的方式工作)。
还是这是monoTouch的线程问题和实现?有任何建议吗?
提前致谢。
拉那
我对IMvxLocationWatcher
实现的线程模型不熟悉。但是,您可能会在UI线程上获得更好的结果(并且绝对会有更好的性能):
protected internal static Task<MvxGeoLocation> GetCurrentLocationAsync()
{
var tcs = new TaskCompletionSource<MvxGeoLocation>();
const int timeoutInMs = 5000;
var locationWatcher = Mvx.Resolve<IMvxLocationWatcher>();
locationWatcher.Start(new MvxLocationOptions {Accuracy = MvxLocationAccuracy.Coarse},
// success
location => tcs.TrySetResult(location),
// fail
error => tcs.TrySetException(error));
return tcs.Task;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句