我在桌面應用程序中編寫代碼,將在警車中使用新的Windows Geolocation API。我爲Geolocator.PositionChanged
事件編寫了一個事件監聽器,但它沒有被調用。在我閱讀文檔時,Gelocator
似乎只在位置發生變化時引發此事件。異步調用異步方法
我覺得我的程序在完成設置事件監聽器後應該做的第一件事是調用Geolocator.GetPositionAsync
方法獲取當前位置,然後讓位置在它們發生時進行更新。我需要同步調用Geolocator.GetPositionAsync
方法。爲此,我寫了下面的方法:
private async Task<Geoposition> GetCurrentPosition() {
await Geolocator.GetGeopositionAsync();
}
不過,我得到以下編譯器錯誤就行與await
它:
'await' requires that the type 'Windows.Foundation.IAsyncOperation' have a suitable GetAwaiter method. Are you missing a using directive for 'System'?
這裏有using語句的頂部文件:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using Windows.Devices.Geolocation;
如何解決此編譯器錯誤?
編輯
後,我添加了一個參考System.Runtime.WindowsRuntime.dll
項目,錯誤就走開了。但是,現在我得到一個新的錯誤:
'System.Runtime.CompilerServices.TaskAwaiter`1<Windows.Devices.Geolocation.Geoposition>' does not contain a definition for 'IsCompleted'
我該如何解決這個問題?
編輯
下面是調用該方法的代碼:
protected override void Initialize() {
// Make sure we "forget" any previous Gelocator device
if (Geolocator != null) {
Geolocator.PositionChanged -= PositionChanged;
Geolocator.StatusChanged -= StatusChanged;
Geolocator = null;
}
CurrentPosition = new GpsInformation() { TimeStamp = DateTime.Now };
Geolocator = new Geolocator();
Geolocator.DesiredAccuracy = PositionAccuracy.High; // Sends position updates with the highest accuracy possible.
Geolocator.MovementThreshold = 0; // Sends position updates no matter how far the vehicle has moved since the last update.
Geolocator.ReportInterval = 0; // Sends position updates as they become availble.
Geolocator.PositionChanged += PositionChanged; // Sends position updates to this method.
Geolocator.StatusChanged += StatusChanged; // Sends status changed updates to this method.
switch (Geolocator.LocationStatus) {
case PositionStatus.Disabled:
case PositionStatus.NotAvailable:
// The Geolocator device is disabled. We won't get any updates. Throw an exception.
throw new Exception("LPRCore does not have permission to use Windows Geolocation services or Geolocation services are not working.");
}
Task<Geoposition> getPositionTask = GetCurrentPosition();
positionRecord = getPositionTask.Result;
}
你確定你已經在使用系統;'在同一個文件,你有await表達式?另外請注意,我懷疑你想'返回等待Geolocator.GetGeopositionAsync();' –
是的,我在saem文件中有'using System;'作爲await表達式。我添加了'return'到行,我得到了同樣的錯誤。 –