第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在新線程中運行一些簡單的代碼?

如何在新線程中運行一些簡單的代碼?

慕萊塢森 2019-10-05 10:50:38
我有一些代碼需要在不同于GUI的線程中運行,因為它當(dāng)前導(dǎo)致表單在代碼運行(約10秒左右)時凍結(jié)。假設(shè)我以前從未創(chuàng)建過新線程;在C#中以及如何使用.NET Framework 2.0或更高版本的簡單/基本示例是什么?
查看完整描述

3 回答

?
波斯汪

TA貢獻1811條經(jīng)驗 獲得超4個贊

喬·阿爾巴哈里(Joe Albahari)是開始閱讀的好地方。


如果要創(chuàng)建自己的線程,這很簡單:


using System.Threading;

new Thread(() => 

{

    Thread.CurrentThread.IsBackground = true; 

    /* run your code here */ 

    Console.WriteLine("Hello, world"); 

}).Start();


查看完整回答
反對 回復(fù) 2019-10-05
?
繁星點點滴滴

TA貢獻1803條經(jīng)驗 獲得超3個贊

BackgroundWorker 似乎是您的最佳選擇。


這是我的最小示例。單擊按鈕后,后臺工作人員將開始在后臺線程中工作,并同時報告其進度。工作完成后還將報告。


using System.ComponentModel;

...

    private void button1_Click(object sender, EventArgs e)

    {

        BackgroundWorker bw = new BackgroundWorker();


        // this allows our worker to report progress during work

        bw.WorkerReportsProgress = true;


        // what to do in the background thread

        bw.DoWork += new DoWorkEventHandler(

        delegate(object o, DoWorkEventArgs args)

        {

            BackgroundWorker b = o as BackgroundWorker;


            // do some simple processing for 10 seconds

            for (int i = 1; i <= 10; i++)

            {

                // report the progress in percent

                b.ReportProgress(i * 10);

                Thread.Sleep(1000);

            }


        });


        // what to do when progress changed (update the progress bar for example)

        bw.ProgressChanged += new ProgressChangedEventHandler(

        delegate(object o, ProgressChangedEventArgs args)

        {

            label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);

        });


        // what to do when worker completes its task (notify the user)

        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(

        delegate(object o, RunWorkerCompletedEventArgs args)

        {

            label1.Text = "Finished!";

        });


        bw.RunWorkerAsync();

    }

注意:


為了簡單起見,我使用C#的匿名方法將所有內(nèi)容放在單個方法中,但是您始終可以將它們拉到其他方法中。

在ProgressChanged或  RunWorkerCompleted處理程序中更新GUI是安全的 。但是,從更新GUI DoWork 將導(dǎo)致  InvalidOperationException。


查看完整回答
反對 回復(fù) 2019-10-05
?
慕妹3242003

TA貢獻1824條經(jīng)驗 獲得超6個贊

快速又骯臟,但是可以使用:


在頂部使用:


using System.Threading;

簡單的代碼:


static void Main( string[] args )

{

    Thread t = new Thread( NewThread );

    t.Start();

}


static void NewThread()

{

    //code goes here

}

我只是把它扔到一個新的控制臺應(yīng)用程序中

查看完整回答
反對 回復(fù) 2019-10-05
  • 3 回答
  • 0 關(guān)注
  • 566 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號