Sharpscripts & async ScriptMethods

Hey Demis,
just trying out sharp scripts. We are probably going to use it as our templating engine for different emails/messages.

Is it possible to call an async method from scriptsharp?

Given the following playground:

        public void RenderScriptWithAsyncReturnString()
            var container = AppHost.Instance.Container;
            var context = new ScriptContext()
                ScanAssemblies = { typeof(I18nScript).Assembly },
                Container = container,
            Console.WriteLine(context.RenderScript("hello async {{ 'xxxxx' |> translate }}"));

And the following Script Method

    public class I18nScript : ScriptMethods
        private readonly I18NextNet _i18n;

        public I18nScript(I18NextNet i18n)
            _i18n = i18n;

        public Task<string> Translate(string key)
            return _i18n.TranslateAsync("x", "y", key);

The i18n library uses async.

The output is hello async System.Threading.Tasks.Task1[System.String]`, but obviously should be the awaited result of the Task.

It also doesnt work if i do

        public async Task<string> Translate(string key)
            return await _i18n.TranslateAsync("language", "namespace", key);

How can this be achieved?

Maybe i was blind but I couldn’t figure it out in the docs. Sorry if i missed it there!

It’s async behavior mentioned in the Introduction page, basically await is implicitly called within an template expression when a script method returns a Task<object>.

So you’ll need to change your script methods to return Task<object> where it will be implicitly awaited:

a |> b |> c

When not within a chained template expression e.g. inside a string template literal ${a.b().sync().c()} or block expression #block expr="a.b().Result.c()" you can call .sync() method or the tasks .Result property directly to execute it the Task synchronously.

1 Like

I’ve added more docs to clarify async behavior at:

1 Like

Thank you!

I was actually looking at your DbScripts.cs and saw the Task<object>, but expected then string (or other basic types) to also work. Wasnt paying too much attention to object… Oops!

Btw: intellisense would be great for *.ss :wink: