Skip to main content

C# example of how to run an Async Task, and wait for the result.

private static T RunAsyncTaskAndWait<T>(Task<T> task)
{
    try
    {
        Task.Run(async () => await task.ConfigureAwait(false)).Wait();
        return task.Result;
    }
    catch (AggregateException ae)
    {
        // Any exception thrown as a result of running task will cause
        // AggregateException to be thrown with actual exception as inner.
        throw ae.InnerExceptions[0];
    }
}

//
// Usage:

public static byte[] Decrypt(byte[] encryptedMessage)
{
    if (encryptedMessage == null)
    {
        return null;
    }

    DataProtectionProvider dataProtectionProvider = new DataProtectionProvider(ProtectionDescriptor);
    IBuffer buffer = RunAsyncTaskAndWait(dataProtectionProvider.UnprotectAsync(encryptedMessage.AsBuffer()).AsTask());

    return buffer.ToArray(0, (int)buffer.Length);
}