WinRT Consumer Preview: Calling C# (CSharp) Async class libraries from Javascript WinJS.Promises using then() clause

You probably already know that you can call C# Class Libraries from WinJS. Now that means I can define C# async methods and call it with WinJS.Promises right??

Think about it

This Javascript means the same as the C# counter part.

//C# var csharpclass = new ClassLibrary1.Class1(); await csharpclass.testAsync(); // do something

//javascript var csharpclass = new ClassLibrary1.Class1(); csharpclass.testAsync().then( function (e) { // do something ... });

So does it mean I can avoid creating WinJS.Promises object for async method and use C# instead since it's (let's be honest)  kinda confusing and do this instead?


// to avoid doubt: THIS DOES NOT WORK // only wishful thinking! public sealed class Class1 { public async void testAsync() { // do this asynchronously ... } }

wouldn't that be cool???

Unfortunately not.

to declare an asynchronous method in C# and be able to call it as WinJS.Promises we can't use the async C# keyword but instead use the IAsyncActionWithProgress interface instead. Here's an example:

namespace ClassLibrary1 { public sealed class Class1 { public IAsyncActionWithProgress<Result> testAsync() { return AsyncInfo.Run<Result>((token, result) => Task.Run<Result>(()=> { // do this asynchronously ... return new Result(); } )); } } public sealed class Result { ... } }

Not as clean as one would hope, huh? Hopefully it'll change in the next Windows 8 release and Microsoft will introduce support to async keyword for WinJS.Promises

Tested on Windows 8 Consumer Preview

Read more: Creating Windows Runtime Components in C# and Visual Basic

  1. Steel Castro says:

    C# support many class library and much more..