要使用线程,请在代码中添加以下命名空间-
using System.Threading;
首先,您需要在C#中创建一个新线程-
Thread thread =新线程(threadDemo);
上面,threadDemo是我们的线程函数。
现在将参数传递给线程-
thread.Start(str);
上面设置的参数是-
String str = "你好,世界!";
让我们看完整的代码,以将参数传递给C#中的线程。
using System;
using System.Threading;
namespace Sample {
class Demo {
static void Main(string[] args) {
String str = "你好,世界!";
//新线程
Thread thread =新线程(threadDemo);
//传递参数
thread.Start(str);
}
static void threadDemo(object str) {
Console.WriteLine("Value passed to the thread: "+str);
}
}
}输出结果
Value passed to the thread: 你好,世界!