gpt4 book ai didi

c# - 如何将变量传递给另一个线程

转载 作者:行者123 更新时间:2023-12-04 11:30:57 26 4
gpt4 key购买 nike

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Taking data from Main Thread\n->");
string message = Console.ReadLine();

ThreadStart newThread = new ThreadStart(delegate { Write(message); });

Thread myThread = new Thread(newThread);

}

public static void Write(string msg)
{
Console.WriteLine(msg);
Console.Read();
}
}
}

最佳答案

您也可以使用 CallContext如果您有一些数据想要通过调用序列“流动”一些数据。 Here is a good blog posting about LogicalCallContext from Jeff Richter .

using System;  
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Taking data from Main Thread\n->");
string message = Console.ReadLine();

//Put something into the CallContext
CallContext.LogicalSetData("time", DateTime.Now);

ThreadStart newThread = new ThreadStart(delegate { Write(message); });

Thread myThread = new Thread(newThread);

}

public static void Write(string msg)
{
Console.WriteLine(msg);
//Get it back out of the CallContext
Console.WriteLine(CallContext.LogicalGetData("time"));
Console.Read();
}
}
}

关于c# - 如何将变量传递给另一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3969476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com