Best way to run a simple function on a new Thread?

Malfist picture Malfist · Oct 21, 2009 · Viewed 91k times · Source

I have two functions that I want to run on different threads (because they're database stuff, and they're not needed immediately).

The functions are:

            getTenantReciept_UnitTableAdapter1.Fill(rentalEaseDataSet1.GetTenantReciept_Unit);
            getTenantReciept_TenantNameTableAdapter1.Fill(rentalEaseDataSet1.GetTenantReciept_TenantName);

In javascript, I know I can create create an anonymous function and call it on a new thread quite easily with something like this:

setTimeout(new function(){doSomethingImportantInBackground();}, 500);

Is there something like this in C#?

Answer

Jon Skeet picture Jon Skeet · Oct 21, 2009

Your question isn't very clear, I'm afraid. You can easily start a new thread with some code, using anonymous methods in C# 2, and lambda expressions in C# 3:

Anonymous method:

new Thread(delegate() {
    getTenantReciept_UnitTableAdapter1.Fill(
        rentalEaseDataSet1.GetTenantReciept_Unit);
}).Start();
new Thread(delegate() {
    getTenantReciept_TenantNameTableAdapter1.Fill(
        rentalEaseDataSet1.GetTenantReciept_TenantName);
}).Start();

Lambda expression:

new Thread(() =>
    getTenantReciept_UnitTableAdapter1.Fill(
        rentalEaseDataSet1.GetTenantReciept_Unit)
).Start();
new Thread(() =>
    getTenantReciept_TenantNameTableAdapter1.Fill(
        rentalEaseDataSet1.GetTenantReciept_TenantName)
).Start();

You can use the same sort of syntax for Control.Invoke, but it's slightly trickier as that can take any delegate - so you need to tell the compiler which type you're using rather than rely on an implicit conversion. It's probably easiest to write:

EventHandler eh = delegate
{
    // Code
};
control.Invoke(eh);

or

EventHandler eh = (sender, args) =>
{
    // Code
};
control.Invoke(eh);

As a side note, are your names really that long? Can you shorten them to get more readable code?