标签: task-parallel-library

C#中的并行树遍历

我需要快速遍历一棵树,我想并行完成.我宁愿使用并行扩展而不是手动旋转一堆线程.

我当前的代码看起来像这样:

   public void Traverse(Node root)
    {
        var nodeQueue = new Queue<Node>();
        nodeQueue.Enqueue(root);
        while (nodeQueue.Count!=0)
        {
            var node = nodeQueue.Dequeue();
            if (node.Property = someValue) DoSomething(node);
            foreach (var node in node.Children)
            {
                nodeQueue.Enqueue(node);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我真的希望Parallel.ForEach有一个Parallel.While模拟.我遇到了Stephen Toub关于使用Parallel.ForEach实现Parallels Parallel的文章.如果正确读取它仍然无法工作,因为我正在改变我试图迭代的队列.

我是否需要使用任务工厂和递归(这有风险吗?)?还是有一些我忽略的简单解决方案?

编辑:@svick

该树有超过250,000个节点.现在最大深度是14个节点,包括根.

根目录下有大约500个节点,之后的平衡具有相当随机的分布.我很快就会得到更好的分布统计数据.

@Enigmativity:

是的,许多用户同时修改了树,但我通常会为树或子树提供共​​享读锁,或允许脏读.

对node.Children的调用可以被认为是原子的.

DoSomething实际上是几个代理之一,对于一些昂贵的操作,我可能会收集节点的快照列表并在遍历之外处理它们.

我意识到我应该看一般情况(遍历的子树而不是整个树.)为此,我在树的每个节点上运行遍历并查看总时间.

我为每个遍历算法使用了Parallel.ForEach(nodes,Traverse),其中节点包含所有~250k节点.这模拟(某种程度上)许多用户同时请求许多不同的节点.

00256ms广度优先顺序

00323ms广度优先连续工作(我将静态计数器增加为"工作")

01495ms Kirks第一个回答

01143ms Svicks第二个答案

00000ms Recursive Single Threaded在60s后没有完成

00000ms电子书的答案在60年代后没有完成

@Enigma,我想我可能会以某种方式搞砸你的算法,因为它似乎应该更快.

结果令我惊讶的是至少可以说.为了让自己相信编译器并没有神奇地优化遍历,我不得不在广度第一顺序中添加一些工作.

对于头部的单次遍历,并行化第一级仅具有最佳性能.但几乎没有,这个数字有所改善,因为我向第二级添加了更多节点(2000而不是500).

c# parallel-processing tree-traversal task-parallel-library

13
推荐指数
1
解决办法
5143
查看次数

在任务中发生异常的情况下,根据用户输入多次重试任务

在我的应用程序中的所有服务调用实现为tasks.When永远的任务发生故障,我需要一个对话框,向用户呈现failed.If用户选择重试程序应该重试任务重试最后一次操作,否则记录异常后,程序的执行应该继续.任何人都对如何实现这个功能有了很高的想法?

c# wpf exception-handling task task-parallel-library

13
推荐指数
2
解决办法
1万
查看次数

ConcurrentBag <T>实现中是否存在内存泄漏?

可能重复:
ConcurrentBag中可能的内存泄漏?

EDIT1:

实际的问题是.你能证实这一点,还是我的样本错了,我错过了一些明显的东西?

我认为ConcurrentBag是一个简单的替代无序列表.但是我错了.ConcurrentBag确实将自己作为ThreadLocal添加到创建线程,这基本上会导致内存泄漏.

   class Program
    {
        static void Main(string[] args)
        {
            var start = GC.GetTotalMemory(true);
            new Program().Start(args);
            Console.WriteLine("Diff: {0:N0} bytes", GC.GetTotalMemory(true) - start);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            Thread.Sleep(5000);
        }

        private void Start(string[] args)
        {
            for (int i = 0; i < 1000; i++)
            { 
                var bag = new ConcurrentBag<byte>();
                bag.Add(1);
                byte by;
                while (bag.TryTake(out by)) ;
            }
        }
Run Code Online (Sandbox Code Playgroud)

我可以制作Diff 250 KB或100 GB,具体取决于我添加到包中的数据量.数据和包包都消失了.

当我用Windbg打破这个时,我做了一个!DumpHeap -type Concurrent

....

000007ff00046858        1           24 System.Threading.ThreadLocal`1+GenericHolder`3[[System.Collections.Concurrent.ConcurrentBag`1+ThreadLocalList[[System.Byte, mscorlib]], System],[System.Threading.ThreadLocal`1+C0[[System.Collections.Concurrent.ConcurrentBag`1+ThreadLocalList[[System.Byte, mscorlib]], System]], mscorlib],[System.Threading.ThreadLocal`1+C0[[System.Collections.Concurrent.ConcurrentBag`1+ThreadLocalList[[System.Byte, mscorlib]], System]], mscorlib],[System.Threading.ThreadLocal`1+C0[[System.Collections.Concurrent.ConcurrentBag`1+ThreadLocalList[[System.Byte, mscorlib]], …
Run Code Online (Sandbox Code Playgroud)

.net c# task-parallel-library base-class-library

13
推荐指数
1
解决办法
4608
查看次数

在WPF应用程序中执行后台任务

例

private void Start(object sender, RoutedEventArgs e)
{
    int progress = 0;
    for (;;)
    {
        System.Threading.Thread.Sleep(1);
        progress++;
        Logger.Info(progress);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我想要Start(),建议的方法是什么(TAP或TPL或BackgroundWorker或Dispatcher或其他)

  1. 不要阻止ui线程
  2. 可以提供进度报告
  3. 可以取消
  4. 支持多线程和多核

c# wpf multithreading tap task-parallel-library

13
推荐指数
2
解决办法
3万
查看次数

如何在TPL数据流中将多个目标块与源块链接?

我期望以下两个发布者产生输出,但它只产生第一个的输出:

var broadcastBlock = new BroadcastBlock<int>(null);
var transformBlock = new TransformBlock<int, int>(i => i*10);
var publish1 = new ActionBlock<int>(i => Console.WriteLine("Publisher 1:" + i));
var publish2 = new ActionBlock<int>(i => Console.WriteLine("Publisher 2:" + i));

broadcastBlock.LinkTo(transformBlock, new DataflowLinkOptions() { PropagateCompletion = true });
transformBlock.LinkTo(publish1, new DataflowLinkOptions() { PropagateCompletion = true });
transformBlock.LinkTo(publish2, new DataflowLinkOptions() { PropagateCompletion = true });

foreach (var i in Enumerable.Range(0, 5))
{
    broadcastBlock.Post(i);
}
broadcastBlock.Complete();
Task.WhenAll(publish1.Completion, publish2.Completion).Wait();
Run Code Online (Sandbox Code Playgroud)

我显然在这里缺少一些基本的东西,任何想法?

.net c# task-parallel-library tpl-dataflow

13
推荐指数
1
解决办法
3221
查看次数

应该返回Task的方法抛出异常吗?

返回的方法Task有两个报告错误的选项:

  1. 立刻抛出异常
  2. 返回将以异常结束的任务

调用者是否应该期望两种类型的错误报告,或者是否存在将任务行为限制为第二个选项的某些标准/协议?

例:

class PageChecker {
    Task CheckWebPage(string url) {
        if(url == null) // Argument check
            throw Exception("Bad URL");

        if(!HostPinger.IsHostOnline(url)) // Some other synchronous check
            throw Exception("Host is down");

        return Task.Factory.StartNew(()=> {
            // Asynchronous check
            if(PageDownloader.GetPageContent(url).Contains("error"))
                throw Exception("Error on the page");
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

处理这两种类型看起来很丑陋:

try {
    var task = pageChecker.CheckWebPage(url);

    task.ContinueWith(t =>
        {
            if(t.Exception!=null)
                ReportBadPage(url);
        });

}
catch(Exception ex) {
    ReportBadPage(url);
}
Run Code Online (Sandbox Code Playgroud)

使用async/await可能有所帮助,但有没有异步支持的纯.NET 4解决方案?

.net c# asynchronous .net-4.0 task-parallel-library

13
推荐指数
1
解决办法
3690
查看次数

强制执行一次异步方法

假设我有一个需要使用InitializeAsync()方法执行异步初始化的类.我想确保初始化只执行一次.如果另一个线程在初始化正在进行时调用此方法,它将"等待"直到第一个调用返回.

我正在考虑以下的实现(使用SemaphoreSlim).有更好/更简单的方法吗?

public class MyService : IMyService
{
    private readonly SemaphoreSlim mSemaphore = new SemaphoreSlim(1, 1);
    private bool mIsInitialized;

    public async Task InitializeAsync()
    {
        if (!mIsInitialized)
        {
            await mSemaphore.WaitAsync();

            if (!mIsInitialized)
            {
                await DoStuffOnlyOnceAsync();
                mIsInitialized = true;
            }

            mSemaphore.Release();
        }
    }

    private Task DoStuffOnlyOnceAsync()
    {
        return Task.Run(() =>
        {
            Thread.Sleep(10000);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑:

由于我正在使用DI并且将注入此服务,因此将其作为"懒惰"资源使用或使用异步工厂对我来说不起作用(尽管在其他用例中它可能很好).因此,异步初始化应该封装在类中,并对IMyService消费者透明.

将初始化代码包装在"虚拟" AsyncLazy<>对象中的想法将完成这项工作,尽管对我来说感觉有点不自然.

.net c# asynchronous task-parallel-library async-await

13
推荐指数
3
解决办法
2301
查看次数

如何实现异步File.Delete/Create/Move?

由于我必须在我的应用程序中执行大量文件I/O操作,因此我决定异步实现它们.查看MSDN,File.Create,File.Delete和File.Move没有异步对应项.据我所知,原因是不存在用于文件删除,创建或移动的异步Win32实现,所以我最终得到了以下解决方案:

public static Task DeleteAsync(string path)
{
     Guard.FileExists(path);

     return Task.Run(() => File.Delete(path));
}

public static Task<FileStream> CreateAsync(string path)
{
     Guard.IsNotNullOrWhitespace(path);

     return Task.Run(() => File.Create(path));
}

public static Task MoveAsync(string sourceFileName, string destFileName)
{
     Guard.FileExists(sourceFileName);
     Guard.IsNotNullOrWhitespace(destFileName);

     return Task.Run(() => { File.Move(sourceFileName, destFileName); });
}
Run Code Online (Sandbox Code Playgroud)

考虑到范例"不要在库中使用Task.Run",我想知道是否有更好的实现或者我应该回退到同步代码?

提前谢谢了!

编辑:


  • 根据Peter Duniho的建议改进了代码
  • 添加了由Sriram Sakthivel提供的原始博客文章的链接

c# io asynchronous task-parallel-library async-await

13
推荐指数
1
解决办法
1万
查看次数

多个线程将元素添加到一个列表.为什么列表中的项目总是少于预期?

以下代码解释了我的问题.我知道列表不是线程安全的.但是这个潜在的"真正"原因是什么?

    class Program
{
    static void Main(string[] args)
    {
        List<string> strCol = new List<string>();

        for (int i = 0; i < 10; i++)
        {
            int id = i;
            Task.Factory.StartNew(() =>
            {
                AddElements(strCol);
            }).ContinueWith((t) => { WriteCount(strCol, id.ToString()); });
        }

        Console.ReadLine();
    }

    private static void WriteCount(List<string> strCol, string id)
    {
        Console.WriteLine(string.Format("Task {0} is done. Count: {1}. Thread ID: {2}", id, strCol.Count, Thread.CurrentThread.ManagedThreadId));
    }

    private static void AddElements(List<string> strCol)
    {
        for (int i = 0; i < 20000; i++)
        {
            strCol.Add(i.ToString());
        } …
Run Code Online (Sandbox Code Playgroud)

c# parallel-processing concurrency multithreading task-parallel-library

12
推荐指数
2
解决办法
1万
查看次数

如何使用Task.Run(Action <T>)

我正在尝试创建一个接受TcpClient连接的方法,并在客户端连接后执行任务"ConnectedAction".我在尝试创建一个新任务来运行委托"ConnectedAction"时收到编译错误.

参数1:无法从'void'转换为'System.Func'

我相信这个错误是因为该方法试图运行"ConnectedAction"方法并将void返回给Task.Run参数.

如何让Task运行"ConnectedAction"委托?

class Listener
{
    public IPEndPoint ListenerEndPoint {get; private set;}
    public int TotalAttemptedConnections { get; private set; }
    public Action<TcpClient> ConnectedAction { get; private set; }

    public Listener(IPEndPoint listenerEndPoint, Action<TcpClient> connectedAction)
    {
        ConnectedAction = connectedAction;
        ListenerEndPoint = listenerEndPoint;

        Task.Factory.StartNew(Listen, TaskCreationOptions.LongRunning);
    }

    private void Listen()
    {
        TcpListener tcpListener = new TcpListener(ListenerEndPoint);
        tcpListener.Start();

        while (true)
        {
            TcpClient tcpClient = tcpListener.AcceptTcpClient();
            TotalAttemptedConnections++;

            //Error here 
            Task.Run(ConnectedAction(tcpClient));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# delegates compiler-errors task-parallel-library

12
推荐指数
1
解决办法
1万
查看次数