c# - 异步委托(delegate)与线程/线程池?

标签 c# .net multithreading

我需要执行 3 个并行任务,每个任务完成后,它们应该调用同一个函数来打印结果。

我不明白在 .net 中为什么我们有异步调用(delegate.BeginInvoke() & delegate.EndInvoke())以及 Thread 类?

我有点困惑什么时候使用哪一个?现在在这种特殊情况下,我应该使用异步调用还是 Thread 类?

我正在使用 C#。

最佳答案

<强>1。异步委托(delegate)

Asychronous calling is used when you have work items that should be handled in the background and you care when they finish.

BackgroundWorker vs background Thread

<强>2。后台 worker

  • Use BackgroundWorker if you have a single task that runs in the background and needs to interact with the UI. and use it if you don't care when they finish their task. The task of marshalling data and method calls to the UI thread are handled automatically through its event-based model.
  • Avoid BackgroundWorker if (1) your assembly does not already reference the System.Windows.Form assembly, (2) you need the thread to be a foreground thread, or (3) you need to manipulate the thread priority.

<强>3。线程池

  • Use a ThreadPool thread when efficiency is desired. The ThreadPool helps avoid the overhead associated with creating, starting, and stopping threads.
  • Avoid using the ThreadPool if (1) the task runs for the lifetime of your application, (2) you need the thread to be a foreground thread, (3) you need to manipulate the thread priority, or (4) you need the thread to have a fixed identity (aborting, suspending, discovering).

<强>4。线程类

  • Use the Thread class for long-running tasks and when you require features offered by a formal threading model, e.g., choosing between foreground and background threads, tweaking the thread priority, fine-grained control over thread execution, etc.

关于c# - 异步委托(delegate)与线程/线程池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1837962/

相关文章:

javascript - 如何解决 ASP.NET 使用子目录时的相对 url 问题?

c# - 叶节点类中的 sealed 关键字

c# - 没有指定authenticationScheme,也没有找到默认认证和自定义授权的DefaultChallengeScheme

c# - 为什么缓冲区大小会改变我的流输出?

java - 如何在我的线程中断后立即中断 RestTemplate 调用?

c# - Observable 中的通知并行性

c++ - std::thread 和 std::mutex 问题

c# - Dockerfile 看不到本地文件或私有(private) nuget 服务器

java - 没有泛型的愚蠢证明迭代的API设计

c# - 使用 DryIoc 创建具有多个服务注册的单例