等待DeviceInformation.FindAllAsync(selector)时引用System.Runtime.

本文关键字:引用 System Runtime selector DeviceInformation FindAllAsync 等待 | 更新日期: 2023-09-27 18:18:01

我正在写一个桌面应用程序的代码,用于发现和连接带有Windows 10 Wi-Fi Direct的设备。我遵循了如何从非winrt环境中调用Windows运行时API的说明,除了以下几行外,在VS 2013上一切都很好,我将它们移动到针对。net Framework 4.5的控制台应用程序中:

using System;
using Windows.Devices.Enumeration;
using Windows.Devices.WiFiDirect;
static void Main()
{
    DoSomethingAsync().Wait();
}
static async void DoSomethingAsync()
{
    var selector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.DeviceInterface);
    foreach (var info in await DeviceInformation.FindAllAsync(selector)) // <-- error
    {
        ...
    }
}

错误仍然是

'await'要求类型' Windows.Foundation.IAsyncOperation<Windows.Devices.Enumeration.DeviceInformationCollection> '有一个合适的GetAwaiter方法。您是否缺少using指令"系统"?

包含以下库引用:

  • 系统。运行时,C:'Program Files (x86)'Reference Assemblies'Microsoft'Framework.NETFramework'v4.5'Facades'System.Runtime.dll
  • System.Runtime。WindowsRuntime, C:'Program Files (x86)'Reference Assemblies'Microsoft'Framework.NETCore'v4.5' system . runtime . windowsrtime .dll
  • 窗口。设备,C:'Windows'System32' WinMetadata ' Windows.Devices.winmd
  • 窗口。基金会C:'Windows'System32' WinMetadata ' Windows.Foundation.winmd

我确信selector可以正确检索(如

)
System.Devices.InterfaceClassGuid:="{439B20AF-8955-405B-99F0-A62AF0C68D43}" 
AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True

),那么我假设这个黑客对Windows 10的桌面应用程序仍然有效。

如何修复此错误?

等待DeviceInformation.FindAllAsync(selector)时引用System.Runtime.

非常感谢@Yuval Itzchakov, @vidalsasoon

原来我被System.Runtime.WindowsRuntime.dll所在的路径误导了。在C:'Program Files (x86)'Reference Assemblies'Microsoft'Framework'.NETCore'v4.5中,库实际上是。net Framework 4.0,其中没有定义这样的扩展方法(GetWaiter, AsTask…)。然而,当你在VS.

中引用。net Framework程序集时,看起来文件夹是默认位置。

然后我引用

  • System.Runtime.WindowsRuntime.dll, of C:'Windows'Microsoft.NET'Framework'v4.0.30319'System.Runtime.WindowsRuntime.dll
  • Windows, of C:'Program Files (x86)'Windows Kits'10'UnionMetadata'Windows.winmd

尝试在IAsyncOperation中添加"AsTask()",并解决Yuval提到的问题。

static void Main()
{
    var selector = WiFiDirectDevice.GetDeviceSelector();
    var findAllDevicesTask = DeviceInformation.FindAllAsync().AsTask();
    Task.WaitAll(findAllDevicesTask);
    for (var info in findAllDevicesTask.Result)
    {
        ...
    }
}