我有一些代码需要在与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
}
我把它扔进了一个新的控制台应用程序中
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/3195374