#
Async Support
h5 provides robust support for asynchronous programming using the async and await keywords, leveraging JavaScript's native Promise API under the hood.
#
Async/Await
You can write asynchronous code in C# just as you would in a typical .NET application.
public async Task<string> FetchDataAsync(string url)
{
var response = await Http.GetAsync(url);
return response.Text;
}
public async void Main()
{
try
{
string data = await FetchDataAsync("https://api.example.com/data");
Console.WriteLine(data);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
#
How It Works
When you compile code with async/await, h5 transforms the state machine generated by the C# compiler into a sequence of JavaScript Promises.
Task: Maps directly to a JavaScriptPromise.Task<T>: Maps to aPromisethat resolves to a value of typeT.void: Maps to aPromisethat resolves toundefined(fire-and-forget).
#
Interoperating with JavaScript Promises
Since Task is implemented as a Promise, you can easily interoperate with existing JavaScript libraries that return Promises.
#
Consuming a Promise
If an external JavaScript function returns a Promise, you can await it directly if you type it as Task or Task<T>.
[External]
public static class MyJsLib
{
public static extern Task<int> LongRunningOperation();
}
// Usage
int result = await MyJsLib.LongRunningOperation();
#
Returning a Promise
Similarly, if your C# method returns a Task, it can be consumed by JavaScript code as a Promise.
public async Task<string> GetData()
{
await Task.Delay(1000);
return "Hello from C#";
}
// JavaScript
MyNamespace.MyClass.GetData().then(result => {
console.log(result); // "Hello from C#"
});
#
Task.Delay
Task.Delay is implemented using setTimeout.
await Task.Delay(1000); // Waits for 1 second
#
Considerations
- Threading: Remember that JavaScript is single-threaded. While
awaityields execution, it does not run on a background thread. Long-running synchronous operations will block the UI. - Task.Run:
Task.Runexecutes the delegate immediately on the current "thread" (the main JS thread), but wrapped in a Promise. It does not offload work to a worker thread automatically.