我就呵呵了,敢不敢贴代码 using System; using System.IO; using System.Threading; using System.Linq;public static class Program { static void Doing(int i) { Console.WriteLine(Thread.CurrentThread.ManagedThreadId); Console.WriteLine(i.ToString()); } public static void Main(String[] args) { try { for (int i = 0; i < 10; i++) { //代码A Action<int> action = new Action<int>(Doing); action.BeginInvoke(i, null, null); }
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
在Main里面也加上。如果一致,就是一个线程,不一致,就是多个线程。
对啊,不是多线程,你以为呢。你要是要用多线程,需要用Task或者Thread
对啊,不是多线程,你以为呢。你要是要用多线程,需要用Task或者Thread
尴尬,还以为是多线程的。我还顺便把1楼给感谢了,真是悲催。
using System;
using System.IO;
using System.Threading;
using System.Linq;public static class Program
{
static void Doing(int i)
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(i.ToString());
}
public static void Main(String[] args)
{
try
{
for (int i = 0; i < 10; i++)
{
//代码A
Action<int> action = new Action<int>(Doing);
action.BeginInvoke(i, null, null);
}
Console.WriteLine("循环结束...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
}
}输出
自己看MSDN怎么说:使用异步方式调用同步方法
赞。以程序为准。
大哥,你试试再打印线程那行前面随便加些东西,比如aaa之类的,然后拼接当前线程Id试试。
大哥,你试试再打印线程那行前面随便加些东西,比如aaa之类的,然后拼接当前线程Id试试。
你想表达什么?
另外,主线程也就是执行For循环的线程一般是ID1
当前线程id碰巧在1-10之间,正好跟打印i的值(也在1-10之间)混在一起,你还怎么区分哪个是线程的id?但是你把它换成:Console.WriteLine(“aaa : ”+Thread.CurrentThread.ManagedThreadId);
即使你循环10000次,仍然是同一个。
iyomumx是对的,正确的检测方法确实应该放在Doing方法内。这说明Action.BeginInvoke确实是多线程。
版主是让在方法内加的,我自己没看仔细,就放在了for循环内。我的错。我的错。万分抱歉,两位。今晚这这几个小时,学习了。向两位作揖,拜谢!结贴。
9楼iyomumx的仍然可判断出线程的Id,即使没有添加前缀。因为有数字重复,可作为依据。这是我的错误之一。
版主在开头即明确告知,在方法内,加上获取线程Id的方法,我自己疏忽,放在了for循环内。这是我的错误之二。
有两位传道授业解惑的师者给了方法,我盲目的进行测试,没有理性、仔细的进行分析处理。这是我的错误之三。希望后来者,在看到这篇帖子时,注意下这个总结。也希望自己以后不要再干这样的蠢事。
最后深深的感谢iyomumx,感谢。感谢斑竹在最近几篇帖子中的回复。感谢。
单纯for直接打印数字的话,是线性。如果去掉直接打印,改用Action.BeginInvoke,应该属于并行了吧。当然Parallel.For是并行的,这个我用过。我用BeginInvoke的主要目的是想知道,此方法是否为多线程。
手动写10个Thread和扔十个任务跟线程池其实执行过程是不一样的,因为线程池线程都是默认后台线程,且有任务队列调配。
{
Console.WriteLine(i.ToString());
}
里面可以加个sleep 随机阻塞几百ms
这样玩起多线程 才会清楚一点.