Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metro - write async c# operation and call from javascript

I have create a metro app which is composed by - a c# windows runtime component - a javascript application, wich contains the UI and is the main application.

In the c# component I created an async method:

async public void createDocument() {
}

but when I try to call it from the javascript code, I cannot use the .done() or the then() function to handle the method completed evet, because there is an error: javascript error, cannot call done() from object not set to an instance of object.

If I try to assign Task or Task to the function I have another error, which tell me Task is not a windows runtime type and to use IAsyncOperation, IAsyncAction, ecc.. instead.

So, how can I create an async function in the c# windows runtime component and call it from javascript handling the done() or then() events?

like image 934
Marco Avatar asked Feb 03 '26 22:02

Marco


1 Answers

I found an article that seems to be related to the problem you are having. I haven't done this myself, but the gist of it says that you can't use the async keyword from C# for Javascript promises - you must wrap the method in a slightly different way:

instead of:

public sealed class Class1
{
    public async void testAsync()
    {
        // do this asynchronously ...
    }
}

try:

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 { ... }
    }

I copied and pasted the examples from this article by Ronald Widha - http://www.ronaldwidha.net/2012/05/10/winrt-consumer-preview-calling-c-csharp-async-class-libraries-from-javascript-winjs-promises-using-then-clause/ It was written during the consumer preview, so it might have changed between then and the final release

Hopefully that will help you a bit more!

like image 162
GracelessROB Avatar answered Feb 06 '26 10:02

GracelessROB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!