【问题标题】:C# "await" error when using WinRT from Desktop app从桌面应用程序使用 WinRT 时出现 C#“等待”错误
【发布时间】:2014-03-04 10:47:19
【问题描述】:

我尝试使用 C# 中的 Windows 运行时从桌面应用程序获取我的 GPS 位置。

我跟随this how-to 设置Visual Studio 和this code sample 创建以下琐碎代码作为C# 控制台应用程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using System.IO;
using System.Runtime;
using System.Windows;

using Windows;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Foundation.Collections;

namespace GeoLocCS
{
    public sealed partial class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            Console.Read(); 
        }
    }

    public class Test
    {
        private Geolocator geolocator;

        public Test()
        {
            Console.WriteLine("test");
            geolocator = new Geolocator();

            this.getPos();
        }

        async void getPos()
        {
            Geoposition pos = await geolocator.GetGeopositionAsync();
            Console.WriteLine(pos.Coordinate.Latitude.ToString());
        }
    }
}

尝试编译时,出现错误:

Error 1 'await' requires that the type 'Windows.Foundation.IAsyncOperation<Windows.Devices.Geolocation.Geoposition>' have a suitable GetAwaiter method. Are you missing a using directive for 'System'?

我尝试引用每个可以引用的 DLL,例如“System.runtime”、“System.Runtime.WindowsRuntime”、“Windows.Foundation”...

我错过了什么?

谢谢你的回答,

谢尔盖

【问题讨论】:

  • 听起来像重复,我想stackoverflow.com/questions/13125793/… 可能会给你一个解决方案
  • @RemcoBrilstra 我也希望它会,但没有。我尝试引用System.Runtime.WindowsRuntime.dll,但仍然收到错误。

标签: c# geolocation windows-runtime async-await


【解决方案1】:

我终于找到了我的问题:

  • 我使用的是 8.1,所以我在 .csproj 文件 (targetingPlatform) 中更改了此设置,而不是针对 8.0
  • 修改后,我可以引用“Windows”
  • 我手动引用了以下两个 DLL:

    C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\Facades\System.Runtime.dll

    C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Runtime.WindowsRuntime.dll

【讨论】:

  • 这解决了我的问题!一切都是从 2011 年开始的,对于 Windows 8.0,非常感谢您!
【解决方案2】:

如果你是 Win8.1 请使用:

<TargetPlatformVersion>8.1</TargetPlatformVersion>

而不是 8.0。

【讨论】:

    【解决方案3】:

    添加到现有答案:

    我突然在 WPF 中使用多项目解决方案遇到了这个问题(仍然不知道为什么)。我尝试在 TargetPlatformVersions 8.1 和 10.0 之间切换,尝试使用 v4.5- 和 v4.5.1-System.Runtime.WindowsRuntime.dll,总是在 BadImageFormatException 和 FileNotFoundException 之间交替。

    原来是某些 app.config 文件(不是 .csproj 文件!)中的引用。 Visual Studio 2017 一定是在某个时候添加了它们,一旦我删除了这些条目,上述解决方案终于奏效了。

    【讨论】:

    • 你是对的,在我的情况下,设置 &lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7"/&gt; 会导致问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多