Search code examples
c#asp.nettaskfire-and-forget

Fire & Forget method using Task.Run not working


I read a lot of codes trying to use Task.Run without success.

What I want to achive:

  • In an ASP.NET WebForm event (click event handler) call a Fire & Forget method (not block the current flow of execution).

What I tried and don't understant why it's not working:


First Version:

protected void btn_Click(object sender, EventArgs e)
{
    // Some actions
    // Should insert a record in database --> OK

    //Tried this call with and without ConfigureAwait(false)
    Task.Run(() => MyClass.doWork()).ConfigureAwait(false);

    // Should insert a record in database --> OK
    // Some actions not blocked by the previous call
}

public static class MyClass
{
    public static void doWork()
    {
        // Should insert a record in database --> NOT INSERTED
    }
}


Second Version:

protected void btn_Click(object sender, EventArgs e)
{
    // Some actions
    // Should insert a record in database --> OK

    Bridge.call_doWork();

    // Should insert a record in database --> OK
    // Some actions not blocked by the previous call
}

public static class Bridge
{
    public static async Task call_doWork()
    {
        //Tried this call with and without ConfigureAwait(false)
        await Task.Run(() => MyClass.doWork()).ConfigureAwait(false);
    }
}

public static class MyClass
{
    public static void doWork()
    {
        // Should insert a record in database --> NOT INSERTED
    }
}

So I call the Fire & Forget method, which should insert a record in the database, but there's no record inserted.

The inserts before and after the call to the Fire & Forget method are done.

I don't know how to resolve my issue.


Solution

  • HttpContext will not be available in threads other than the main thread, so you can't depend on it.

    But you can pass data from HttpContext to your method when you start the task. For example:

    Task.Run(() => MyClass.doWork(HttpContext.Current.Session["somedata"])).ConfigureAwait(false);