我有一些代码须要在与GUI不一样的线程中运行,由于它当前致使表单在代码运行时冻结(10秒左右)。 spa
假设我之前从未建立过新的线程; 什么是如何在C#中使用.NET Framework 2.0或更高版本执行此操做的简单/基本示例? 线程
若是你想获得一个值: 代理
var someValue; Thread thread = new Thread(delegate() { //Do somthing and set your value someValue = "Hello World"; }); thread.Start(); while (thread.IsAlive) Application.DoEvents();
Joe Albahari是开始阅读的好地方。 code
若是你想建立本身的线程,这很简单: get
using System.Threading; new Thread(() => { Thread.CurrentThread.IsBackground = true; /* run your code here */ Console.WriteLine("Hello, world"); }).Start();
这是另外一种选择: string
Task.Run(()=>{ //Here is a new thread });
尝试使用BackgroundWorker类。 您能够为代理人提供运行的内容,并在工做完成时收到通知。 我连接到的MSDN页面上有一个示例。 it
快速又脏,但它会起做用: io
在顶部使用: thread
using System.Threading;
简单代码: 表单
static void Main( string[] args ) { Thread t = new Thread( NewThread ); t.Start(); } static void NewThread() { //code goes here }
我把它扔进了一个新的控制台应用程序中