Tag: task parallel library

如果发生某些错误,则在后台重新启动任务

我正在使用一些使用Mono.Mac(3.2.3)的REST请求与服务器通信,作为重试机制,我正在悄悄地尝试在HTTP操作失败或超时的情况下多次尝试。 我有以下几点; var tries = 0; while (tries ALLOWED_TRIES) { throw new Exception(“Failed to access Resource.”, e); } } } 任务使用父方法的参数如此; var postTask = new Task(() => {return someStuff(foo, bar);}, Task.Factory.CancellationToken, Task.Factory.CreationOptions); 问题似乎是任务不希望在第一次完成(以及后续失败)后使用postTask.Start()再次运行。 有没有一种简单的方法可以做到这一点,还是我以这种方式滥用任务? 是否有某种方法将任务重置为初始状态,或者我最好使用某种工厂?

如何计算.NET应用程序中的并发线程数量?

阅读Parallel.ForEach后继续产生新线程我仍然怀疑它是否是计算并发线程数的正确方法? 我看到的是,该方法计算Parallel.ForEach中同时输入但未完成的迭代(循环)的数量。 它是传递正确数量的同时运行线程的并发线程数的同义词吗? 我不是专家,但我可以想象: 线程可以重新使用,而其活动在某处交换以便以后继续。 从理论上讲,用于循环活动的线程在循环完成后保留在线程池中,但不会重新用于另一个循环 或者有什么可能扭曲实验的纯度(线程计数)? 无论如何,如何直接计算.NET进程的运行线程数,最好是(C#)代码? 更新: 所以,如果要遵循Jeppe Stig Nielsen的回答并使用计数 directThreadsCount = Process.GetCurrentProcess().Threads.Count; 然后输出,在Release(threadsCount == 7)和Debug(threadsCount == 15)模式下非常相似: [Job 0 complete. 2 threads remaining but directThreadsCount == 7 [Job 1 complete. 1 threads remaining but directThreadsCount == 7 [Job 2 complete. 2 threads remaining but directThreadsCount == 7 [Job 4 complete. 2 threads […]

Parallel.For不使用我的主线程

在我的应用程序中,我希望我的主线程不被其他任何东西使用。 我必须做一些并行处理,我希望由不同的线程完成。 为此,我使用Parallel.For如下 static void SomeMethod() { Console.WriteLine(string.Format(“Main Thread ID before parallel loop ->>>>>>> {0} “, System.Threading.Thread.CurrentThread.ManagedThreadId)); Parallel.For(0, 10, i => { Console.WriteLine(string.Format(“Output ->>>>>>> {0} “, System.Threading.Thread.CurrentThread.ManagedThreadId)); }); Thread.Sleep(100); Console.WriteLine(string.Format(“Main Thread ID after parallel loop ->>>>>>> {0} “, System.Threading.Thread.CurrentThread.ManagedThreadId)); } 从输出主线程可以看出使用ThreadID 1和Parallel.For中的一些线程也使用相同的线程。 Main Thread ID before parallel loop ->>>>>>> 1 Output ->>>>>>> 1 Output ->>>>>>> […]

为什么块按此顺序运行?

这是一个简短的代码示例,可以快速向您介绍我的问题: using System; using System.Linq; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; namespace DataflowTest { class Program { static void Main(string[] args) { var firstBlock = new TransformBlock(x => x, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 }); var secondBlock = new TransformBlock(async x => { if (x == 12) { await Task.Delay(5000); return $”{DateTime.Now}: Message is {x} (This […]

是否有默认方式获得成功完成的第一个任务?

让我们说我有几个任务: void Sample(IEnumerable someInts) { var taskList = someInts.Select(x => DownloadSomeString(x)); } async Task DownloadSomeString(int x) {…} 我想得到第一个成功任务的结果。 所以,基本的解决方案是写下这样的东西: var taskList = someInts.Select(x => DownloadSomeString(x)); string content = string.Empty; Task firstOne = null; while (string.IsNullOrWhiteSpace(content)){ try { firstOne = await Task.WhenAny(taskList); if (firstOne.Status != TaskStatus.RanToCompletion) { taskList = taskList.Where(x => x != firstOne); continue; } […]

任务中的秒表似乎是所有任务的附加,想要测量任务间隔

我正在循环运行并以下列方式启动任务: var iResult = new List(); foreach(var i in myCollection) { var task = Task.Factory.StartNew(() => DoSomething(), TaskCreationOptions.LongRunning); task.ContinueWith(m => myResponseHandler(m.Result)); iResult.Add(task); } 在我的DoSomething()方法中,我有一个计时器: public static myMsg DoSomething() { var timer = System.Diagnostics.Stopwatch.StartNew(); DoLongRunningTask(); //If it matters this hits a REST endpoint (https) timer.Stop(); return new myMsg(timer.ElaspedMilliseconds); } 当我遍历myMsg的列表时, myMsg似乎完全是加法的 – 第一个上的ElaspedMilliseconds可能是300,但最后一个可能是50000(50秒) – 这实际上是整个事情需要的大致时间运行(由另一个计时器测量)。

仅当任务未在指定时间内完成时才显示进度对话框

我有一个上传图像的servlets,我这样使用它: ImageInfo result = await service.UploadAsync(imagePath); 我想要做的是显示进度对话框,但前提是上传操作需要超过2秒。 上传完成后,我想关闭进度对话框。 我使用Task / ContinueWith做了一个粗略的解决方案,但我希望有一种更“优雅”的方式。 如何使用async/await实现此目的?

一个任务可以有多个等待者吗?

我正在为Windows 8项目提供异步服务,并且有一些此服务的异步调用,一次只能调用一次。 public async Task CallThisOnlyOnce() { PropagateSomeEvents(); await SomeOtherMethod(); PropagateDifferentEvents(); } 由于你无法在锁定语句中封装异步调用,我想到使用AsyncLock模式,但我认为我可能会尝试这样的事情: private Task _callThisOnlyOnce; public Task CallThisOnlyOnce() { if(_callThisOnlyOnce != null && _callThisOnlyOnce.IsCompleted) _callThisOnlyOnce = null; if(_callThisOnlyOnce == null) _callThisOnlyOnce = CallThisOnlyOnceAsync(); return _callThisOnlyOnce; } private async Task CallThisOnlyOnceAsync() { PropagateSomeEvents(); await SomeOtherMethod(); PropagateDifferentEvents(); } 因此,最终只能同时执行CallThisOnlyOnceAsync调用,并且多个awaiters挂钩在同一个Task上。 这是一种“有效”的方法吗?或者这种方法有一些缺点吗?

如何并行启动List ?

我有一个返回System.Threading.Tasks.Task的对象: public class MyClass { public Task GetTask(object state, CancellationToken cancellationToken) { return new Task(Execute, state, cancellationToken); } public void Execute(object context) { //do stuff } } 在其他地方我有一个List ,所以我执行以下操作来获取List : var myTaskList = myClassList.Select(p => p.GetTask(null, cancellationToken)).ToList(); 现在我有List ,如何并行启动它们? 是否有更简洁的方法来编码? 谢谢!

如何使用任务并行库(TPL)实现重试逻辑

可能重复: 如果任务中发生exception,则根据用户输入多次重试任务 我正在寻找一种在TPL中实现重试逻辑的方法。 我想有一个generics函数/类,它将能够返回一个将执行给定操作的Task,并且在exception的情况下将重试该任务,直到给定的重试计数。 我尝试使用ContinueWith进行播放,并且在出现exception时让回调创建一个新任务,但它似乎只适用于固定数量的重试。 有什么建议? private static void Main() { Task taskWithRetry = CreateTaskWithRetry(DoSometing, 10); taskWithRetry.Start(); // … } private static int DoSometing() { throw new NotImplementedException(); } private static Task CreateTaskWithRetry(Func action, int retryCount) { }