Tuesday, 24 November 2009

How to Fire and Forget a Method Asyncronously

Problem:
Fire and forget the following method:

public void SendEmail(string message, string to)
{
// logic
}

Approach 1: using BackgroundWorker class

public class SendEmailArgument
{
public string Message { get; set; }

public string To { get; set; }
}

var argument = new SendEmailArgument() {Message = "My message", To = "name@domain.com"};

var bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync(argument);

static void bw_DoWork(object sender, DoWorkEventArgs e)
{
var argument = (SendEmailArgument) e.Argument;
SendEmail (argument.Message, argument.To);
}

Approach 2: Using ThreadPool class

Approach 3: Using Thread class

No comments: