Tag: task parallel library

在C#内部使用TPL内部服务的基本设计模式

我正在尝试构建Windows服务,它需要某种并行性来汇集来自不同ftp源的文件。 为了启动多个ftp下载,我正在寻找TPL库来轻松地进行foreach循环并使并行性变得非常容易。 但是当我搜索如何启动或停止我的服务时,我最好的资金是在OnStart()方法中创建新线程,如下所述https://stackoverflow.com/a/4865893/69433 阅读有关TPL的信息,请注意TPL比手动线程和手动停止线程更先进。 我没有找到任何描述如何在WindowsService中进行TPL循环的示例post? 我的代码: protected override void OnStart(string[] args) { _thread = new Thread(WorkerThreadFunc); _thread.Name = “My Worker Thread”; _thread.IsBackground = true; _thread.Start(); } 而在WorkerThreadFunc里面做了那种TPL private void WorkerThreadFunc() { foreach (string path in paths) { string pathCopy = path; var task = Task.Factory.StartNew(() => { Boolean taskResult = ProcessPicture(pathCopy); return taskResult; }); task.ContinueWith(t […]

如何在控制台应用程序中从Task.WaitAll()获取返回值?

我使用控制台应用程序作为概念certificate和获得异步返回值的新需求。 我发现我需要在main方法中使用Task.WaitAll()来避免需要异步“main()”方法,这是非法的。 我现在卡住试图弄清楚允许我使用generics的重载,或者只返回我可以强制转换的对象,但是在Main()中。

展平处理的AggregateExceptions

我遇到了一些我在AggregateException上调用flatten问题,但是里面仍然存在另一个AggregateException ! 这显然意味着它们正在链中传播并被转换为另一个AggregateException 。 有没有办法递归展平所有内部AggregateExceptions? 通常,我将使用handle delegate来处理这些,但如果有另一个内部AggregateExceeption则返回false。 我没有正确处理这些问题吗? 编辑:因为我已经在调用Flatten,所以看起来问题是它直到稍后在callstack中被捕获。 这是我正在调用Flatten()的代码。 要在堆栈跟踪中使用,此方法称为WriteExceptionRecord(string,FileInfo): do { try { using (var stream = file.Open(FileMode.Append, FileAccess.Write, FileShare.None)) { using (StreamWriter writer = new StreamWriter(stream)) { await writer.WriteLineAsync(data); } } } catch (AggregateException ex) { ex.Flatten().Handle((x) => { if (x is IOException) { retryNeeded = true; retryLeft–; Thread.Sleep(500); return true; } […]

具有指定结果的任务并行库WaitAny

我正在尝试编写一些代码,这些代码将使Web服务并行调用多个不同的服务器,因此TPL似乎是一个明显的选择。 只有我的一个Web服务调用将返回我想要的结果,而其他所有调用都不会。 我正在尝试找到一种有效地拥有Task.WaitAny的方法,但只有在匹配条件的第一个Task返回时才会解锁。 我尝试过WaitAny但无法确定filter的位置。 我到目前为止: public void SearchServers() { var servers = new[] {“server1”, “server2”, “server3”, “server4”}; var tasks = servers .Select(s => Task.Factory.StartNew(server => CallServer((string)server), s)) .ToArray(); Task.WaitAny(tasks); //how do I say “WaitAny where the result is true”? //Omitted: cancel any outstanding tasks since the correct server has been found } private bool CallServer(string […]

如何释放Parallel.Task使用的内存?

我有一个程序进行内存密集型模拟。 下面我写了一个小型控制台应用程序,它复制了我遇到的问题。 class Program { static void Main(string[] args) { var t = new Task(() => DoMemoryHog(20000000)); t.Start(); t.Wait(); t.Dispose(); t = null; GC.Collect(); Console.WriteLine(“Done”); Console.ReadLine(); } static void DoMemoryHog(int n) { ConcurrentBag results = new ConcurrentBag(); Parallel.For(0, n, (i) => { results.Add(Math.Sqrt(i.GetHashCode())); }); } } 当我运行程序时,我可以看到Windows任务管理器中已用内存量的增加,但是当任务完成(并显示“完成”)时,内存不会恢复到原始级别,只会发生当我关闭应用程序时。 有没有人知道如何释放并行任务使用的内存,而主应用程序一直在运行? 正如你所看到的,我已经尝试过处理它,将它的引用设置为null并手动运行垃圾收集器(我知道你不应该这样做)。

你如何捕获CancellationToken.Register回调exception?

我使用异步I / O与HID设备通信,我想在超时时抛出一个可捕获的exception。 我有以下读取方法: public async Task Read( byte[] buffer, int? size=null ) { size = size ?? buffer.Length; using( var cts = new CancellationTokenSource() ) { cts.CancelAfter( 1000 ); cts.Token.Register( () => { throw new TimeoutException( “read timeout” ); }, true ); try { var t = stream.ReadAsync( buffer, 0, size.Value, cts.Token ); await […]

为什么Task.WaitAll()不会阻塞或导致死锁?

在下面的示例中,使用了两个await调用。 为了获得性能,样本转换为Task.WaitAll() (实际上没有更快,但这只是一个例子)。 这是来自Android上使用Sqlite.Net的库中的代码,该方法从主UI线程上的OnResume()调用: public async Task SetupDatabaseAsync() { await CreateTableAsync(); await CreateTableAsync(); } 这是替代方案: public void SetupDatabaseAsync() { var t1 = CreateTableAsync(); var t2 = CreateTableAsync(); Task.WaitAll(t1, t2); } 但是根据我的理解, Task.WaitAll()应该在等待时阻止UI线程,从而导致死锁。 但它的工作正常。 那是因为这两个调用实际上并没有在UI线程上调用任何东西吗? 如果我使用Task.WhenAll()而不是有什么区别? 我猜它即使调用UI线程也能工作,就像await 。

使用blockingcollection和tasks .net 4 TPL的经典生产者消费者模式

请参阅下面的伪代码 //Single or multiple Producers produce using below method void Produce(object itemToQueue) { concurrentQueue.enqueue(itemToQueue); consumerSignal.set; } //somewhere else we have started a consumer like this //we have only one consumer void StartConsumer() { while (!concurrentQueue.IsEmpty()) { if (concurrentQueue.TrydeQueue(out item)) { //long running processing of item } } consumerSignal.WaitOne(); } 我如何移植我从远古时代以来使用的模式来使用taskfactory创建的任务和net 4的新信号function。换句话说,如果有人用net 4编写这个模式,它会是什么样子? 伪代码很好。 我已经使用了.net 4 […]

我如何等到任务在C#中完成?

我想向服务器发送请求并处理返回的值: private static string Send(int id) { Task responseTask = client.GetAsync(“aaaaa”); string result = string.Empty; responseTask.ContinueWith(x => result = Print(x)); responseTask.Wait(); // it doesn’t wait for the completion of the response task return result; } private static string Print(Task httpTask) { Task task = httpTask.Result.Content.ReadAsStringAsync(); string result = string.Empty; task.ContinueWith(t => { Console.WriteLine(“Result: ” + […]

可移植类库,相当于Dispatcher.Invoke或Dispatcher.RunAsync

在.NET,Windows 8和Windows Phone 7中,我的代码与此类似: public static void InvokeIfRequired(this Dispatcher dispatcher, Action action) { if (dispatcher.CheckAccess()) { action(); } else { dispatcher.Invoke(action); } } 我如何在便携式类库中做一些事情? 有一个平台无关的实现这将是很好的。 我的想法是使用WP7中没有的TPL,但肯定会很快。 // PortableDispatcher must be created on the UI thread and then made accessible // maybe as a property in my ViewModel base class. public class PortableDispatcher { private TaskScheduler […]