C# 程式向執行緒傳遞引數


要使用執行緒,在程式碼中新增以下名稱空間 -

using System.Threading;

首先,你需要在 C# 中建立一個新執行緒 -

Thread thread = new Thread(threadDemo);

上面,threadDemo 是我們的執行緒函式。

現在,將一個引數傳遞給執行緒 -

thread.Start(str);

上面設定的引數是 -

String str = "Hello World!";

示例

讓我們來看看將一個引數傳遞給 C# 中執行緒的完整程式碼。

即時演示

using System;
using System.Threading;
namespace Sample {
   class Demo {
      static void Main(string[] args) {
         String str = "Hello World!";
         // new thread
         Thread thread = new Thread(threadDemo);
         // passing parameter
         thread.Start(str);
      }
      static void threadDemo(object str) {
         Console.WriteLine("Value passed to the thread: "+str);
      }
   }
}

輸出

Value passed to the thread: Hello World!

更新於: 19-6 月-2020

4K+ 訪客

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.