6,298 questions
0
votes
1
answer
123
views
Why are items not written to console immediately after being processed?
I have the following C# code :
var rand = new Random(1);
var range = Enumerable.Range(1, 8);
var partition = Partitioner.Create(range, EnumerablePartitionerOptions.NoBuffering);
foreach (var x in ...
1
vote
2
answers
175
views
Task in C# is cancelling by itself [duplicate]
I have some code in a dll project with the target as .Net 8.
In my code there is an async method called EmailNonError which is being called with the following code. When this code executes, the email ...
0
votes
1
answer
59
views
WhenAll nested in WhenAny (or WhenAll with timeout) [duplicate]
The first exception does not block the execution:
public static async Task Main()
{
await Task.WhenAny(
Task.WhenAll(
Task.Run(() => throw new Exception(&...
0
votes
0
answers
108
views
Hope to cope with exceptions inside tasks
Here's my example code. It's of no use, but it's short.
I have an array to switch on or off the creation of Exceptions at different parts of my code and two functions. The first (Level 0) is an ...
0
votes
2
answers
96
views
Crucial differences of await keyword and ContinueWith()
For the following code snippets, I'm wondering what the actual differences are, when they are executed.
The first snippet using await:
public async Task LoadAsync()
{
task = loader.LoadAsync(...);
...
1
vote
1
answer
135
views
How does TaskCompletionSource work when an exception occurs?
I'm trying to understand how exception handling works with TaskCompletionSource and await in a console application (which has no SynchronizationContext).
I've written simple code that waits for a ...
0
votes
1
answer
208
views
Why does Task.WhenAll fail to Complete when all its input tasks are completed if locks are involved
See below for complete minimal repro (net9 console project).
When it deadlocks, and I attach a debugger, I can see that the only input task to the whenAllTask is completed, yet the whenAllTask itself ...
2
votes
1
answer
137
views
Task.WhenEach is appending to the task list safe?
Take the example below with the new Task.WhenEach method
List<Task<List<int>>> tasks =
[
MyTask()
];
await foreach (var task in Task.WhenEach(tasks))
{
var result = await ...
0
votes
1
answer
86
views
AsParallel.ForAll with async code doesn't wait for completion [duplicate]
I've got some code which uses AsParallel().ForAll(...) which I was led to believe would block while all of the executions completed. This works perfectly with non async code.
For example the below ...
2
votes
1
answer
190
views
How to wrap a Task in a Task<TResult> without using an async state machine?
I want to wrap a Task in a Task<TResult> without using an async state machine, while preserving the original task's properties. Based on What's the best way to wrap a Task as a Task<TResult&...
0
votes
0
answers
57
views
How can I create a delay task which contains a result value? [duplicate]
I have an override method which looks like this:
public override Task Start(CancellationToken cancellationToken)
{
return Task.Delay(1000,cancellationToken);
}
However the abstract class ...
1
vote
3
answers
254
views
Why are Minimal API endpoints waiting for Tasks?
Building a basic ASP.NET Core Minimal API, I was surprised by the fact that if an endpoint returns a Task, the request does not return until the Task is done:
var builder = WebApplication....
1
vote
2
answers
113
views
Why do `ParallelQuery.ToArray()` and `ToList()` return ordered sequence?
The doc listed the operators in the table that ToArray should be unordered when the parallelquery source is unordered. However, the result turned out to be always ordered when force evaluated to array ...
0
votes
2
answers
120
views
Any side effects when writing LINQ-like extensions for Task<IEnumerable<T>>?
I'm a little bit annoyed of parentheses in situations like this:
var items = (await SomeService.GetDataAsEnumerableAsync()).ToList();
So I thought of creating an extension method like:
public static ...
1
vote
2
answers
71
views
Task.WaitAll does not throw as expected
I was expecting Task.WaitAll to throw when semaphore reaches its maxcount, but the result is, all tasks were hanged.
SemaphoreSlim semaphore = new(initialCount: 3, maxCount: 10);
var tasks = ...
1
vote
2
answers
123
views
Executing mixed tasks in parallel
I have ~10000 objects of type System.Text.Json.JsonDocument. For each JsonDocument in parallel, I have to do the following steps in order.
Clone JsonDocument to JsonNode
Apply a sequence of tasks ...
0
votes
1
answer
101
views
Why does Task.Factory.StartNew for an async lambda work, when calling the lambda directly does not?
I'm writing a console application that needs to copy console input one keypress at a time to a socket (while also doing other things). In order to do that, I figure I have a couple options. In the ...
0
votes
2
answers
141
views
Task.WhenAny with Task.Delay to implement a timeout mechanism does not work reliable
From within my ASP.NET application (.NET Framework 4.8) I invoke an external process via Anonymous Pipes. Theoretically, it could happen that the external process hangs (for whatever reason) when my ...
1
vote
1
answer
220
views
Passing CancellationTokenSource to awaited Task
Read a lot of articles an watch many videos on Task Cancelation.
But I still can't quite follow if it's possible to pass CancellationTokenSource instead of
CancellationTokenSource providing that the ...
1
vote
1
answer
80
views
Why can't I catch AbandonedMutexException after a task
I was expecting to trigger a AbandonedMutexException after a task that does not release the mutex, the program stuck when WaitOne after the task:
Mutex mutex = new();
BankAccount account = new();
...
0
votes
0
answers
52
views
Deadlock issue when scheduling task computations (F#, .NET TPL)
I am in the process of building an effect system DSL with F# inspired by ZIO and Cats Effect.
I have my effect type defined as a DU of opcodes, a fiber type, a channel type for message passing, etc. I ...
2
votes
1
answer
109
views
Why does direct throwing OperationCanceledException cancels the task [duplicate]
I read the documentation says to set status to Canceled requires three conditions:
OperationCanceledException(or its derived exception type such as TaskCanceledException) is thrown
token....
1
vote
2
answers
149
views
AggregateException is not caught
I have a problem with AggregateException thrown from .NET library. For some reason it is not caught in try-catch block. It causes whole application to crash and there are no methods from my code in ...
1
vote
2
answers
126
views
How to implement a custom Task.WhenAll that preserves the order of exceptions?
The behavior of the non-generic Task.WhenAll changed in .NET 8, and now the order of the exceptions is in chronological order instead of positional order. The new behavior is not without merits, but I ...
0
votes
0
answers
93
views
Where is the difference between await Task Event and Event.Wait
I have a communications driver.
It was failing a few thousand times a day.
But after changing a single line, it now works perfectly.
// The event is set after 100ms at the latest
ManualResetEvent ...
0
votes
2
answers
146
views
Task issue with Powershell and TaskScheduler
I am writing a C# library (.NET 4.6.1) that will use Tasks to be able to run several snippets of code in the background. This library will be called by a Powershell script that is triggered from a ...
0
votes
1
answer
311
views
Problems implementing properly a Parallel.ForΕach loop and continue other work in the mean time
We are using the .Net Framework 4.8.2. For some part of the app I want to execute many long running CPU and IO bound processes (illustrated by Thread.Sleep()) in parallel. That's why I use the ...
0
votes
1
answer
72
views
What is expected output? [duplicate]
Unexpected (for me) output.
The code is:
public static async Task Main()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i=0; i<1000; i++)
...
0
votes
1
answer
38
views
How to preload all the files in a TPL DataFlow pipeline between two TranformBlocks before processing their content?
I have a TPL DataFlow pipeline that parses msbuild project files in order to obtain the location of the respective binary and then processes these binaries.
Here is how it looks like:
var linkOptions =...
-2
votes
2
answers
148
views
What's the best way to Run a Task that is returned by a Method?
Trying to run a Task returned by a Method and get the Result,
How do you run the returned Task and get the result?
using System;
using System.Threading.Tasks;
public class Program
...
0
votes
3
answers
266
views
Understanding multiple consecutive await statements
I was playing around with the ContinueWith function and I ended up not understanding it.
In this example code:
var s = Task.FromResult(true).ContinueWith(async t => t).ContinueWith(async t => t);...
1
vote
2
answers
128
views
Self-Cancelling Task Inhibits other Instances
I am trying to make a subclass of Task that cancels itself and waits when it is disposed.
While unit testing I got strange failing test cases. In the end it boiled down to repetition; I could even run ...
0
votes
3
answers
297
views
What is the difference between a loop and a Task.WhenAll?
I have a method inside which there is a foreach loop, inside the loop I call several asynchronous operations. I asked ChatGPT to do a review, and he said that you can improve performance by adding ...
1
vote
0
answers
67
views
Join block not invoked although the two calling blocks exited successfully
I have 2 transform blocks that are joined into a join block but I sometimes have an issue where both transform blocks finish successfully and the join block is not invoked.
Relevant code snippet and ...
0
votes
0
answers
81
views
Task.Run with and without async delegate [duplicate]
I don't understand clearly difference between almost following Task asynchronous code execution.
Only difference is the async keyword as parameter.
Example - I think this code inside Task run will ...
0
votes
1
answer
103
views
elastic-apm-agent in .net 6 generates a lot of Microsoft-Windows-DotNETRuntime/ExceptionThrown events
We use prometheus-net.DotNetMetrics for system monitoring in ASP .net6 application. And when we started using Elastic Apm agent for .net, the dotnet_exceptions_total metric began to show increased ...
0
votes
0
answers
64
views
TPL Dataflow WPF - Block is getting hosed up while await for Task to complete - .NET Framework 4.8
I am writing a File Transfer Pipeline using TPL library. I am new to this types of implementation so my issue could be related to something I am not aware of. Part of my application allows users to ...
1
vote
1
answer
67
views
Split big CSV file and multithread upload with low footprint
I'm trying to split big CSV files into smaller files and send them to azure storage account, all at the same.
I pretty much read the big file (source) record by record and write it to a temp local ...
1
vote
1
answer
145
views
Ensure that dotnet Tasks are stopped when they go out of garbage collector scope
I have a background task that I am modeling with a Task and which is stopped with an IAsyncDisposable.
// implementation
public sealed class Worker : IAsyncDisposable
{
private readonly ...
1
vote
4
answers
173
views
What is the proper way to convert Task to Task<T>?
I use a library that takes Task<T>, but sometimes I have to pass just Task, which I have to convert to Task<int>. What would be the more efficient/recommended option for converting the ...
0
votes
0
answers
968
views
Resetting/reusing a TaskCompletionSource
I have ClassA that has a property called GetData that returns a TaskCompletionSource Task:
private TaskCompletionSource<Data> _taskCompletionSource = new();
public Task<Data> GetData => ...
0
votes
0
answers
26
views
Task.WaitAll using Task.Run with async/await vs without [duplicate]
I am trying to understand how the code below would behave differently if the functions used in Task.Run were not async/await when calling GetAllData.
Am I correct that GetAllData will behave the same ...
1
vote
2
answers
322
views
How to produce multiple outputs in TPL Dataflow block before completion
I have this case where I am trying to build a pipeline using TPL Dataflow that could process a big number of items. At some point in the pipeline I need to batch items and send to the next block after ...
0
votes
2
answers
108
views
Writing repeating parallel loops for animation, avoiding System.Threading.Tasks.Parallel.For
I am writing a plugin to Rhino which animates some ray-traced data. Rhino handles all the drawing; I just have to provide it with something to draw.
The following Animate function is called from the ...
-1
votes
2
answers
155
views
Avoid closures when calling Parallel.For()
I'm performing some element UI hit testing like this:
internal MyElement[] HitTest((double x, double y) point, double scale)
{
ConcurrentBag<MyElement> geoms = new ConcurrentBag<...
0
votes
2
answers
205
views
Options to achieve parallel execution in C#
I have a use case where I need to process n number of operations, which involves other I/O operations.
Method 1: Uses ConcurrentBag<T>.
But worried that the I/O operations in the ...
0
votes
0
answers
51
views
Using TPL Dataflow with IDisposable
I have a multi-step, branching pipeline using TPL Dataflow, that I would like to get working with Unified Logging (through Azure Application Insights).
My issue is that the APIs at my disposal (no pun ...
-1
votes
2
answers
92
views
Parallel Tasks - Run Parallel threads but dont wait for other Tasks to complete and get the latest data from database
I am using Task library for running multiple tasks parallelly, and I am using below code to wait for other tasks to complete.
Parallel.ForEach(DatafromDB,
item => { DownloadSSR(mediator, ...
1
vote
3
answers
206
views
Parallel.ForEach with retries not showing all the values
I implemented a sample application to see the behavior of the retries inside a Parallel.ForEach loop. As per my observations following application not showing all the values inside the array, in the ...
0
votes
2
answers
1k
views
Async/Await exception handling confusion
I'm trying to understand async/await in .net8, especially exception handling and I'm running into some confusion, especially regarding the documentation as while it specifies some of the approach it ...