public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); for (int i = 0; i < 20; i++) { aa.Post(i); } } //这里要改掉,用委托,不用这个 static ConcurrentDictionary<string, ActionBlock<int>> ss = new ConcurrentDictionary<string, ActionBlock<int>>(); ActionBlock<int> aa = new ActionBlock<int>((i) => { if (decimal.Remainder(i, 2) == 0) { if (!ss.ContainsKey("2")) { ActionBlock<int> a2 = new ActionBlock<int>((ii) => { Console.WriteLine(string.Format("{0}+{1}+{2:ss}", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), ii, DateTime.Now)); }); ss.TryAdd("2", a2); } ss["2"].Post(i); } else { if (!ss.ContainsKey("0")) { ActionBlock<int> a2 = new ActionBlock<int>((ii) => { Console.WriteLine(string.Format("{0}+{1}+{2:ss}", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), ii, DateTime.Now)); }); ss.TryAdd("0", a2); } ss["0"].Post(i); } }); } class ListOrder { public string product { get; set; } public int lastvalue { get; set; } } }
不明白你的具体意思。
合并两个线程 用委托
这是两个线程分别打印 怎样一起打印出来
希望用到委托
@玉赛: 什么叫一起打印?
@519740105: http://tech.ddvip.com/2009-06/1244877836123602.html
像这样一样, 而这里两个数据集 怎样合并到一起打印出来
@玉赛: 下面代码是否你需要的?
private void Run() { Action<int> threadAction = (i) => { Console.WriteLine(string.Format("{0}+{1}+{2:ss}", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), i, DateTime.Now)); }; Action<int, ActionBlock<int>> postAction = (i, actionBlock) => { actionBlock.Post(i); }; ActionBlock<int> actionBlock2 = new ActionBlock<int>(threadAction); ActionBlock<int> actionBlock0 = new ActionBlock<int>(threadAction); Action<int> entryAction = (i) => { if (decimal.Remainder(i, 2) == 0) { postAction(i, actionBlock2); } else { postAction(i, actionBlock0); } }; ActionBlock<int> actionBlockEntry = new ActionBlock<int>(entryAction); for (int i = 0; i < 20; i++) { actionBlockEntry.Post(i); } }
@519740105: 谢谢你哦 跪谢
@玉赛: 下面一个也是可以参考的:
private void Run2() { ActionBlock<int> thread1 = new ActionBlock<int>((Action<int>)Output); ActionBlock<int> thread2 = new ActionBlock<int>((Action<int>)Output); ActionBlock<object> post = new ActionBlock<object>((Action<object>)Post); for (int i = 0; i < 20; i++) { post.Post(new object[] { i, thread1, thread2 }); } } private void Post(object state) { object[] states = state as object[]; int i = (int)states[0]; int index; if (decimal.Remainder(i, 2) == 0) { index = 1; } else { index = 2; } (states[index] as ActionBlock<int>).Post(i); } private void Output(int i) { Console.WriteLine(string.Format("{0}+{1}+{2:ss}", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), i, DateTime.Now)); }
@519740105: 少了委托 委托2个线程的数据 一起输出
@玉赛: 你的输出不是在控制台吗?他们的输出是在一起的啊?你要的“一起输出”是什么概念?
什么是合并2个线程?听都没听说过