gpt4 book ai didi

c# - 用于处理列表的C#异步选项

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

我试图更好地了解C#中的Async和Parallel选项。在下面的代码片段中,我包括了我遇到最多的5种方法。但是我不确定该选择哪个-或者更好的选择时要考虑的标准:

方法1:任务

(请参阅http://msdn.microsoft.com/en-us/library/dd321439.aspx)

Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution. However, unless creation and scheduling must be separated, StartNew is the recommended approach for both simplicity and performance.

TaskFactory's StartNew method should be the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, the constructors may be used, and the task's Start method may then be used to schedule the task for execution at a later time.


// using System.Threading.Tasks.Task.Factory
void Do_1()
{
var _List = GetList();
_List.ForEach(i => Task.Factory.StartNew(_ => { DoSomething(i); }));
}

方法2:QueueUserWorkItem

(请参阅 http://msdn.microsoft.com/en-us/library/system.threading.threadpool.getmaxthreads.aspx)

You can queue as many thread pool requests as system memory allows. If there are more requests than thread pool threads, the additional requests remain queued until thread pool threads become available.

You can place data required by the queued method in the instance fields of the class in which the method is defined, or you can use the QueueUserWorkItem(WaitCallback, Object) overload that accepts an object containing the necessary data.


// using System.Threading.ThreadPool
void Do_2()
{
var _List = GetList();
var _Action = new WaitCallback((o) => { DoSomething(o); });
_List.ForEach(x => ThreadPool.QueueUserWorkItem(_Action));
}

方法3:Parallel.Foreach

(请参阅: http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach.aspx)

The Parallel class provides library-based data parallel replacements for common operations such as for loops, for each loops, and execution of a set of statements.

The body delegate is invoked once for each element in the source enumerable. It is provided with the current element as a parameter.


// using System.Threading.Tasks.Parallel
void Do_3()
{
var _List = GetList();
var _Action = new Action<object>((o) => { DoSomething(o); });
Parallel.ForEach(_List, _Action);
}

方法4:IAsync.BeginInvoke

(请参阅: http://msdn.microsoft.com/en-us/library/cc190824.aspx)

BeginInvoke is asynchronous; therefore, control returns immediately to the calling object after it is called.


// using IAsync.BeginInvoke()
void Do_4()
{
var _List = GetList();
var _Action = new Action<object>((o) => { DoSomething(o); });
_List.ForEach(x => _Action.BeginInvoke(x, null, null));
}

方法5:BackgroundWorker

(请参阅: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx)

To set up for a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.


// using System.ComponentModel.BackgroundWorker
void Do_5()
{
var _List = GetList();
using (BackgroundWorker _Worker = new BackgroundWorker())
{
_Worker.DoWork += (s, arg) =>
{
arg.Result = arg.Argument;
DoSomething(arg.Argument);
};
_Worker.RunWorkerCompleted += (s, arg) =>
{
_List.Remove(arg.Result);
if (_List.Any())
_Worker.RunWorkerAsync(_List[0]);
};
if (_List.Any())
_Worker.RunWorkerAsync(_List[0]);
}
}

我想显而易见的标准是:
  • 在性能方面是否比其他更好?
  • 在错误处理方面是否比其他更好?
  • 在监视/反馈方面是否比其他更好?

  • 但是,您的如何选择
    预先感谢您的见解。

    最佳答案

    您的第一个,第三个和第四个示例隐式使用ThreadPool,因为默认情况下,任务是在ThreadPool上安排的,而TPL扩展也使用ThreadPool,因此该API仅隐藏了一些复杂性,请参见herehere。 BackgroundWorkers是ComponentModel命名空间的一部分,因为它们旨在在UI场景中使用。

    关于c# - 用于处理列表的C#异步选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7322943/

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