我有一些代码,我需要运行在不同的线程,而不是GUI,因为它目前导致窗体冻结,而代码运行(10秒左右)。

假设我以前从未创建过一个新线程;有什么简单/基本的例子,如何做到这一点在c#和使用。net Framework 2.0或更高版本?


当前回答

如果你打算使用原始线程对象,那么你需要将IsBackground设置为true,你还应该设置Threading Apartment模型(可能是STA)。

public static void DoWork()
{
    // do some work
}

public static void StartWorker()
{
    Thread worker = new Thread(DoWork);
    worker.IsBackground = true;
    worker.SetApartmentState(System.Threading.ApartmentState.STA);
    worker.Start()
}

如果你需要UI交互,我会推荐BackgroundWorker类。

其他回答

ThreadPool。QueueUserWorkItem对于简单的东西来说是非常理想的。唯一需要注意的是从另一个线程访问控件。

System.Threading.ThreadPool.QueueUserWorkItem(delegate {
    DoSomethingThatDoesntInvolveAControl();
}, null);

这是另一种选择:

Task.Run(()=>{
//Here is a new thread
});

又快又脏,但很管用:

用于顶部:

using System.Threading;

简单的代码:

static void Main( string[] args )
{
    Thread t = new Thread( NewThread );
    t.Start();
}

static void NewThread()
{
    //code goes here
}

我只是将其放入一个新的控制台应用程序中作为示例

如果你想得到一个值:

var someValue;

Thread thread = new Thread(delegate()
            {                 
                //Do somthing and set your value
                someValue = "Hello World";
            });

thread.Start();

while (thread.IsAlive)
  Application.DoEvents();

如果你打算使用原始线程对象,那么你需要将IsBackground设置为true,你还应该设置Threading Apartment模型(可能是STA)。

public static void DoWork()
{
    // do some work
}

public static void StartWorker()
{
    Thread worker = new Thread(DoWork);
    worker.IsBackground = true;
    worker.SetApartmentState(System.Threading.ApartmentState.STA);
    worker.Start()
}

如果你需要UI交互,我会推荐BackgroundWorker类。