如何在新线程中运行一些简单的代码?

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

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


慕莱坞森
浏览 534回答 3
3回答

波斯汪

乔·阿尔巴哈里(Joe Albahari)是开始阅读的好地方。如果要创建自己的线程,这很简单:using System.Threading;new Thread(() => {    Thread.CurrentThread.IsBackground = true;     /* run your code here */     Console.WriteLine("Hello, world"); }).Start();

繁星点点滴滴

BackgroundWorker 似乎是您的最佳选择。这是我的最小示例。单击按钮后,后台工作人员将开始在后台线程中工作,并同时报告其进度。工作完成后还将报告。using System.ComponentModel;...&nbsp; &nbsp; private void button1_Click(object sender, EventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; BackgroundWorker bw = new BackgroundWorker();&nbsp; &nbsp; &nbsp; &nbsp; // this allows our worker to report progress during work&nbsp; &nbsp; &nbsp; &nbsp; bw.WorkerReportsProgress = true;&nbsp; &nbsp; &nbsp; &nbsp; // what to do in the background thread&nbsp; &nbsp; &nbsp; &nbsp; bw.DoWork += new DoWorkEventHandler(&nbsp; &nbsp; &nbsp; &nbsp; delegate(object o, DoWorkEventArgs args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BackgroundWorker b = o as BackgroundWorker;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // do some simple processing for 10 seconds&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i <= 10; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // report the progress in percent&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b.ReportProgress(i * 10);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.Sleep(1000);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; // what to do when progress changed (update the progress bar for example)&nbsp; &nbsp; &nbsp; &nbsp; bw.ProgressChanged += new ProgressChangedEventHandler(&nbsp; &nbsp; &nbsp; &nbsp; delegate(object o, ProgressChangedEventArgs args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; // what to do when worker completes its task (notify the user)&nbsp; &nbsp; &nbsp; &nbsp; bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(&nbsp; &nbsp; &nbsp; &nbsp; delegate(object o, RunWorkerCompletedEventArgs args)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label1.Text = "Finished!";&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; bw.RunWorkerAsync();&nbsp; &nbsp; }注意:为了简单起见,我使用C#的匿名方法将所有内容放在单个方法中,但是您始终可以将它们拉到其他方法中。在ProgressChanged或&nbsp; RunWorkerCompleted处理程序中更新GUI是安全的 。但是,从更新GUI DoWork 将导致&nbsp; InvalidOperationException。

慕妹3242003

快速又肮脏,但是可以使用:在顶部使用:using System.Threading;简单的代码:static void Main( string[] args ){&nbsp; &nbsp; Thread t = new Thread( NewThread );&nbsp; &nbsp; t.Start();}static void NewThread(){&nbsp; &nbsp; //code goes here}我只是把它扔到一个新的控制台应用程序中
打开App,查看更多内容
随时随地看视频慕课网APP