Get Started!

Fire & Forget a C# Method

When working with long running methods in Web Apps, you might want to fire & forget a method, monitoring the state via another mech.

Using a Task you can fire & forget a method, here's a simple example.

Start with including the required NameSpaces

using System.Threading.Tasks;

In some button handler or other C# method use Task.Run passing a lambda statment of an anonymous function calling the method you want to execute:

/// btnRefreshDataClick, handler for starting Data
/// refresh
public void btnRefreshDataClick(object sender, EventArgs e){

  // Fire & Forget 
  Task.Run( () => {

    // Call the long-running method
    ImportData.ReBuildData(
      "manual",
      Request.Url.Host,
      oSession.oUser.cFullName
    );


  });

  // Don't await the result of the task 
}

You'll probably want to assign the Task to another property or build some lock to control execution, this example assumes the method ReBuildData method controls this locking, which IRL this method does.