Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning Task<string> from async method on Microsoft UWP

I have been trying to return Task from an async method, it creates a folder on a removable device and saves it for future use in the application. However, I am getting the dreaded WME1039, saying I am not using a valid Windows Runtime Type. I have checked here for valid runtime types: Windows Runtime base data types, and string is a valid type.. I am completely stuck and don't really know where to go from here! Am I missing something fundamental with the async/await pattern? My current code is listed below, excuse its roughness, I am simply padding out the concept at the moment!

Calling code:

await LoadExtDrive();

Method:

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

And the build error:

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

Any help would be greatly appreciated, as I am completely confused what this means, let alone why it won't work!

like image 419
Chris Watts Avatar asked Nov 21 '22 02:11

Chris Watts


1 Answers

You can refer to this post: https://marcominerva.wordpress.com/2013/03/21/how-to-expose-async-methods-in-a-windows-runtime-component/

Basically wrap the Task method as private method, and make your public method to return as IAsyncOperation.

like image 104
Shizheng Zhang Avatar answered Dec 18 '22 03:12

Shizheng Zhang