joozek78 / starcounter-async

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Starcounter Async Extensions

Available on nuget: Install-Package Joozek78.Starcounter.Async -Version 1.0.0

To introduce asynchronicity in Starcounter TypedJSON view-model, you have to use callbacks and handle errors carefully:

public void Handle(Input.StartWorkTrigger input)
{
    this.IsBusy = true;
    Task.Run(LengthyJob)
        .ContinueWith(task => Session.ScheduleTask(Session.Current.SessionId,
        (Session session, string sessionId) => {
            // might happen if this code is executed after the session has been destroyed
            if (session == null)
            {
                return;
            }
            try
            {
                // if LengthyJob resulted in exception, it will be unwrapped here
                this.Result = task.Result;
            }
            catch (Exception e)
            {
                this.Result = "Error";
            }
            finally
            {
                this.IsBusy = false;
                // otherwise the changes won't be immediately visible to the client
                session.CalculatePatchAndPushOnWebSocket();
            }
        }));
}

This library allows you to simplify this code by using async-await

public void Handle(Input.StartWorkTrigger input)
{
    AsyncInputHandlers.Run(async () =>
    {
        this.IsBusy = true;
        try
        {
            this.Result = await LengthyJob();
        }
        catch(Exception e)
        {
            this.Result = "Error";
        }
        finally
        {
            this.IsBusy = false;
        }
    });
}

About

License:MIT License


Languages

Language:C# 92.8%Language:HTML 7.2%