运行在一个新的线程的简单功能,最好的方法?最好的、线程、简单、功能

2023-09-03 11:57:48 作者:满眼星河

我有,我想在不同的线程上运行两个功能(因为它们是数据库的东西,和他们没有立即需要的)。

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

的功能是:

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

在JavaScript中,我知道我可以创建创建一个匿名函数,并像这样把它在一个新的线程很容易:

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);

有没有这样的事情在C#?

Is there something like this in C#?

推荐答案

你的问题不是很清楚,我怕。您可以轻松地开始与一些code一个新的线程,使用匿名方法在C#2,和lambda EX pressions在C#3:

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:

匿名方式:

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

LAMBDA EX pression:

Lambda expression:

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

您可以使用相同的语法为 Control.Invoke ,但是它稍微复杂一些的,可以采取的任意的委托 - 所以你需要告诉你正在使用,而不是依赖于隐式转换而键入编译器。这可能是最简单的写:

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);

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

作为一个侧面说明,是你的名字是那么长?可以缩短他们获得更多的可读性code?

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