可以任务最大并行度可以在完成句柄文件后报告



我在我的函数中打开了 n 个并发线程:

List<string> _files = new List<string>();
    public void Start()
    {
        CancellationTokenSource _tokenSource = new CancellationTokenSource();
        var token = _tokenSource.Token;
        Task.Factory.StartNew(() =>
        {
            try
            {
                Parallel.ForEach(_files,
                    new ParallelOptions
                    {
                        MaxDegreeOfParallelism = 5 //limit number of parallel threads 
                    },
                    file =>
                    {
                        if (token.IsCancellationRequested)
                            return;
                        //do work...
                    });
            }
            catch (Exception)
            { }
        }, _tokenSource.Token).ContinueWith(
            t =>
            {
                //finish...
            }
        , TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
        );
            }

有一种方法可以知道,当这个函数仍在处理 1 个文件完成时? 我现在说的是ContinueWith在我的list结束后,情况就是这样。

不确定我是否完全理解您的问题,但您可以通过一种方法使用一些标准通知:

public void Start()
{
    CancellationTokenSource _tokenSource = new CancellationTokenSource();
    var token = _tokenSource.Token;
    Task.Factory.StartNew(() =>
    {
        try
        {
            Parallel.ForEach(_files,
                new ParallelOptions
                {
                    MaxDegreeOfParallelism = 5 //limit number of parallel threads 
                },
                file =>
                {
                    if (token.IsCancellationRequested)
                        return;
                    //do work...
                    OnDone(file);
                });
        }
        catch (Exception)
        { }
    }, _tokenSource.Token).ContinueWith(
        t =>
        {
            //finish...
        }
    , TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
    );
}
public void OnDone(string fileName)
{
    // Update the UI, assuming you're using WPF
    someUIComponent.Dispatcher.BeginInvoke(...)
}

如果更新某些共享状态,则可能需要其他锁,但仅更新 UI(例如,数据网格中的行或列表中的元素)应该没问题,因为同步是由调度程序调用强制执行的。

最新更新