gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:05:59 26 4
gpt4 key购买 nike

我需要执行 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com