首页 新闻 会员 周边 捐助

请问Task.Factory跟 new Task有什么区别?

0
[已解决问题] 解决于 2012-03-19 08:15

请问Task.Factory跟 new Task有什么区别?

C#
tab_china的主页 tab_china | 初学一级 | 园豆:54
提问于:2012-03-16 11:27
< >
分享
最佳答案
0
dudu | 高人七级 |园豆:30948 | 2012-03-16 21:38
其他回答(1)
0
 Action<object> action = (object obj) =>        {            Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId);        };        // Construct an unstarted task        Task t1 = new Task(action, "alpha");        // Cosntruct a started task        Task t2 = Task.Factory.StartNew(action, "beta");        // Block the main thread to demonstate that t2 is executing        t2.Wait();        // Launch t1         t1.Start();
可以 看看這個
無限遐想 | 园豆:3740 (老鸟四级) | 2012-03-16 11:34

谢谢回复,哥们儿,能不能把代码用编辑器插入啊,这样没法看啊

支持(0) 反对(0) tab_china | 园豆:54 (初学一级) | 2012-03-16 11:38
View Code
   static void Main()
{
Action<object> action = (object obj) =>
{
Console.WriteLine("Task={0}, obj={1}, Thread={2}", Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId);
};

// Construct an unstarted task
Task t1 = new Task(action, "alpha");

// Cosntruct a started task
Task t2 = Task.Factory.StartNew(action, "beta");

// Block the main thread to demonstate that t2 is executing
t2.Wait();

// Launch t1
t1.Start();

Console.WriteLine("t1 has been launched. (Main Thread={0})", Thread.CurrentThread.ManagedThreadId);

// Wait for the task to finish.
// You may optionally provide a timeout interval or a cancellation token
// to mitigate situations when the task takes too long to finish.
t1.Wait();

// Construct an unstarted task
Task t3 = new Task(action, "gamma");

// Run it synchronously
t3.RunSynchronously();

// Although the task was run synchrounously, it is a good practice to wait for it which observes for
// exceptions potentially thrown by that task.
t3.Wait();
}


@tab_china: 

支持(0) 反对(1) 無限遐想 | 园豆:3740 (老鸟四级) | 2012-03-16 11:50
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册