Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Async/Await during script execution

Hello joshrmt,

Async/Await is just convenient syntax for creating and consuming methods that use the callback-intensive Tasks API. Instead of returning a normal value, an async method returns a task object that represents the method's execution in the background.

Since JavaScript provides no await syntax, it forces you to deal directly with the task object. As long as you don't simply wait for the task to be completed, your JavaScript code won't hold the thread.

Here's an example. Suppose you have a class with an async method for reading a text file:
publicstaticclass SlowFileReader {
    publicstatic async Task<string> ReadFileAsStringAsync(string path) {
        await Task.Delay(TimeSpan.FromMilliseconds(5000));
        using (var reader = new StreamReader(path)) {
            return await reader.ReadToEndAsync();
Here's how to consume the async method from JavaScript without blocking the thread:
engine.AddHostObject("lib", HostItemFlags.GlobalMembers, new HostTypeCollection("mscorlib"));
engine.AddHostType("SlowFileReader", typeof(SlowFileReader));
    var ReaderCallback = System.Action(System.Threading.Tasks.Task(System.String));
    var readerTask = SlowFileReader.ReadFileAsStringAsync('C:\\Path\\To\\SomeFile.txt');
    readerTask.ContinueWith(new ReaderCallback(function (task) {
The JavaScript code in this example returns immediately, and uses a script delegate to set up a callback into script code. In a real-world scenario you might want to provide a helper method for orchestrating this, rather than exposing all of mscorlib :)

Thanks for your question!

Viewing all articles
Browse latest Browse all 2297