如何在新线程中运行一小段代码?

蹲街弑〆低调 提交于 2020-03-15 18:39:11

我有一些代码需要在与GUI不同的线程中运行,因为它当前导致表单在代码运行时冻结(10秒左右)。

假设我以前从未创建过新的线程; 什么是如何在C#中使用.NET Framework 2.0或更高版本执行此操作的简单/基本示例?


#1楼

如果你想得到一个值:

var someValue;

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

thread.Start();

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

#2楼

Joe Albahari是开始阅读的好地方。

如果你想创建自己的线程,这很简单:

using System.Threading;
new Thread(() => 
{
    Thread.CurrentThread.IsBackground = true; 
    /* run your code here */ 
    Console.WriteLine("Hello, world"); 
}).Start();

#3楼

这是另一种选择:

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

#4楼

尝试使用BackgroundWorker类。 您可以为代理人提供运行的内容,并在工作完成时收到通知。 我链接到的MSDN页面上有一个示例。


#5楼

快速又脏,但它会起作用:

在顶部使用:

using System.Threading;

简单代码:

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

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

我把它扔进了一个新的控制台应用程序中

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!