English 中文(简体)
1. read - 任务。
原标题:Creating threads - Task.Factory.StartNew vs new Thread()

我刚刚在网上学习新的翻新和平行图书馆。

过去,我要像现在这样创造新的通道(例如):

DataInThread = new Thread(new ThreadStart(ThreadProcedure));
DataInThread.IsBackground = true;
DataInThread.Start();

Now I can do:

Task t = Task.Factory.StartNew(() =>
{
   ThreadProcedure();
});

有什么区别?

Thanks

最佳回答

差别很大。 任务安排在ThreadPool上,如果 app,甚至可以执行。

如果您有长期的背景工作,你应利用正确的任务选择来具体阐明这一点。

You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.

问题回答

任务使你完全相信任务。

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it s going to be long-running, say so when you create the task so the task scheduler can take that into account)

请注意,在这两种情况下,您的代码可与方法组别转换相比略为简单:

DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);

在第一种情况下,你只是开始新的透镜,而在第二种情况下,你正在穿透池。

threadgroup work is to share and rerix threads. 它使我们能够避免每当我们需要创造新的线索时损失几毫秒。

进入地下池有几种途径:

  • with the TPL (Task Parallel Library) like you did
  • by calling ThreadPool.QueueUserWorkItem
  • by calling BeginInvoke on a delegate
  • when you use a BackgroundWorker

你的法典第一编告诉《刑法》中心要为你创建一种可以作为背景(在计划T时使用透镜)。 简言之,你明确要求加拿大航天中心为你做一些事情和把起步方法 call起立。

你们的第二套法典是相同的,但代表(简单地说是交接)有责任建立校对(后方又在校方库中运行)和通过“新开车”方法在“工厂”实施过程中的开端。

这是特定编码区之间的迅速差异。 说了这番话后,没有什么详细的区别,或看我的同事的其他答案。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签