开发者

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

开发者 https://www.devze.com 2022-12-08 22:19 出处:网络
I have two functions that I want to run on different threads (because they\'re database stuff, and they\'re not needed immediately).

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(){开发者_JAVA百科doSomethingImportantInBackground();}, 500);

Is there something like this in C#?


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?


Similar to what's been said - I find tasks to be a bit simpler (supported as of .net 4 and can be used as follows as of .net 4.5):

Task mytask = Task.Run(() => 
{
    //Lines of code
});


Starting threads is relatively expensive.

You might be better of using a thread from the thread pool:

ThreadPool.QueueUserWorkItem(unused =>
    getTenantReciept_UnitTableAdapter1.Fill(
        rentalEaseDataSet1.GetTenantReciept_Unit)
);
ThreadPool.QueueUserWorkItem(unused =>
    getTenantReciept_TenantNameTableAdapter1.Fill(
        rentalEaseDataSet1.GetTenantReciept_TenantName)
);


You could use an anonymous method:


void Foo()
{
    Thread myThread = new System.Threading.Thread(delegate(){
              //Your code here
     });
    myThread.Start();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消