C# “await” error when using WinRT from Desktop app

陌路散爱 提交于 2019-12-11 14:18:14

问题


I trying to get my GPS position from a Desktop app, using Windows Runtime, in C#.

I followed this how-to to set up Visual Studio and this code sample to create the following trivial code as a C# console app :

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());
        }
    }
}

When trying to compile, I get the error :

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'?

I tried to reference every DLL that I could, like "System.runtime", "System.Runtime.WindowsRuntime", "Windows.Foundation"...

What I am missing ?

Thanks for the answer,

Serge


回答1:


I finally figured out my problem :

  • I am on 8.1 so I changed this in the .csproj file (targetingPlatform) instead of targeting 8.0
  • After that modification, I could reference "Windows"
  • I manually referenced the two following DLLs :

    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




回答2:


If you are On Win8.1 Please Use:

<TargetPlatformVersion>8.1</TargetPlatformVersion>

and not 8.0.




回答3:


Adding to the existing answers:

I suddenly got this problem with a multiproject solution in WPF (still don't know why). I tried switching between TargetPlatformVersions 8.1 and 10.0, tried using the v4.5- and v4.5.1-System.Runtime.WindowsRuntime.dll, always alternating between BadImageFormatException and FileNotFoundException.

Turned out to be references in some of the app.config-files (not the .csproj-files!). Visual Studio 2017 must have added them at some point and as soon as I removed these entries, the above solutions finally worked.



来源:https://stackoverflow.com/questions/22169782/c-sharp-await-error-when-using-winrt-from-desktop-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!