如何将变量传递给另一个线程 [英] How to Pass a variable to another Thread
本文介绍了如何将变量传递给另一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用系统;使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用的System.Threading;命名空间的ConsoleApplication1
{
类节目
{
静态无效的主要(字串[] args)
{
Console.WriteLine(从主线程\\ N-&GT获取数据;);
字符串消息=到Console.ReadLine(); 的ThreadStart newThread =新的ThreadStart(委托{写(消息);}); 线程MyThread的=新主题(newThread); } 公共静态无效的写(string信息)
{
Console.WriteLine(MSG);
Console.Read();
}
}
}
解决方案
您还可以使用的<一个href=\"http://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.callcontext.aspx?ppud=4\"相对=nofollow> CallContext中如果您有要流有的用您的通话序列数据的一些数据。 <一href=\"http://www.wintellect.com/devcenter/jeffreyr/logical-call-context-flowing-data-across-threads-appdomains-and-processes\"相对=nofollow>这是一个很好的博客杰夫里氏张贴LogicalCallContext。
使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;
使用的System.Threading;命名空间的ConsoleApplication1
{
类节目
{
静态无效的主要(字串[] args)
{
Console.WriteLine(从主线程\\ N-&GT获取数据;);
字符串消息=到Console.ReadLine(); //把东西放入CallContext中
CallContext.LogicalSetData(时间,DateTime.Now); 的ThreadStart newThread =新的ThreadStart(委托{写(消息);}); 线程MyThread的=新主题(newThread); } 公共静态无效的写(string信息)
{
Console.WriteLine(MSG);
//拿回来了CallContext中的
Console.WriteLine(CallContext.LogicalGetData(时代));
Console.Read();
}
}
}
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();
}
}
}
解决方案
You can also use a the CallContext if you have some data that you want to "flow" some data with your call sequence. 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();
}
}
}
这篇关于如何将变量传递给另一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文