从Microsoft UWP上的异步方法返回Task <string>

时间:2016-06-25 17:15:17

标签: c# .net asynchronous uwp windows-10-iot-core

我一直在尝试从异步方法返回Task,它在可移动设备上创建一个文件夹并将其保存以备将来在应用程序中使用。 但是,我得到了可怕的WME1039,说我没有使用有效的Windows运行时类型。我在这里检查了有效的运行时类型: Windows Runtime base data types,字符串是有效类型.. 我完全陷入困境,并且真的不知道从哪里开始!我是否遗漏了async / await模式的基本内容?我现在的代码如下所示,请原谅我的粗糙,我现在只是简单地填写这个概念!

致电代码:

await LoadExtDrive();

方法:

public async Task<string> LoadExtDrive()
{
    StorageFolder externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
    // Get the first child folder, which represents the SD card.
    IReadOnlyList<StorageFolder> tmp;
    try
    {
        tmp = await externalDevices.GetFoldersAsync();
    }
    catch (Exception ex)
    {
        throw;
    }
    StorageFolder sdCard = ( tmp).FirstOrDefault();
    if (sdCard != null)
    {
     // An Removable device is present..
     var dbdir = 
     await sdCard.CreateFolderAsync(APP_DB_DIR_NAME, CreationCollisionOption.OpenIfExists);
     var dirToken = 
     Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(dbdir);
     return dirToken;
    }
    else
    {
        // No SD card is present.
        return null;
    }
}

构建错误:

Error   WME1039 Method 'WebSocketService.StartupTask.LoadExtDrive()' has a parameter of 
type 'System.Threading.Tasks.Task<System.String>' in its signature. Although this generic 
type is not a valid Windows Runtime type, the type or its generic parameters implement 
interfaces that are valid Windows Runtime types.  Consider changing the type 'Task' 
in the method signature to one of the following types instead: 
Windows.Foundation.IAsyncAction, Windows.Foundation.IAsyncOperation, or one of the 
other Windows Runtime async interfaces. The standard .NET awaiter pattern also 
applies when consuming Windows Runtime async interfaces. Please see 
System.Runtime.InteropServices.WindowsRuntime.AsyncInfo for more information 
about converting managed task objects to Windows Runtime async 
interfaces.WebSocketService

任何帮助都会非常感激,因为我完全混淆了这意味着什么,更不用说为什么它不会起作用了!

1 个答案:

答案 0 :(得分:0)

你可以参考这篇文章:https://marcominerva.wordpress.com/2013/03/21/how-to-expose-async-methods-in-a-windows-runtime-component/

基本上将 Task 方法包装为私有方法,并使您的公共方法作为 IAsyncOperation 返回。