Async/Await during script execution

Dec 26, 2013 at 7:09 AM
Edited Dec 26, 2013 at 7:09 AM
I am exposing numerous C# objects to ClearScript using the async/await keywords because they are performing I/O. Will ClearScript properly handle asynchronous methods by returning the thread to the pool properly? Basically I do not want to encounter thread pool starvation due to numerous v8 engines performing I/O at the same time. Thanks!
Coordinator
Dec 28, 2013 at 4:48 PM
Edited Dec 30, 2013 at 2:13 PM
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 it doesn'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:
public static class SlowFileReader {
    public static 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));
engine.Execute(@"
    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) {
        System.Console.WriteLine(task.Result);
    }));
");
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!