Questions tagged [task-parallel-library]
The Task Parallel Library is part of the .NET Framework since .NET 4. It is a set of APIs that simplifies the process of adding parallelism and concurrency to applications.
task-parallel-library
6,253
questions
0
votes
1
answer
44
views
I used "lock" in the "task it doesn't work and race condition occurred
I used "lock" in the "task" it doesn't work and race condition occurred
I have defined a Counter, which should eventually return 0, because a Method increases the value of the ...
0
votes
1
answer
50
views
Parallel.ForEach vs ActionBlock [closed]
For a given MaxDegreeOfParallelism and fixed amount of objects that need to be processed (i.e. have certain code executed on them) it would seem Parallel.ForEach and an ActionBlock would be equally ...
1
vote
1
answer
38
views
Wrapping a task in an async with a timeout?
I would like to run a function in a background thread, then consume the result with a timeout from an async context.
Here is my code:
open System.Threading.Tasks
let forever () =
while true do
(...
1
vote
1
answer
81
views
Employee details becoming null in C# Parallel.ForEach loop when fetching data from API
I have encountered an issue while fetching employee details from an API using a parallel foreach loop in C#. Please note I have used concurrentbag for the tasks to make it thread-safe and adding items ...
1
vote
1
answer
48
views
Creating multiple db connections to get data in Parallel in C# asp.net entity framework
I have a scenario, where in I have to fetch 18000 records from db, and convert it into a DTO. The total number of refIds = 18000 unique ids of the reference table in database.
int batchSize = 1000;
...
0
votes
2
answers
84
views
How to send multiple requests to a server at few milliseconds of interval in C#
I have a code that looks like this:
public static async Task<Request> SendRequest(Client client, DateTime startTime, int offset)
{
TimeSpan timeToWait = startTime - DateTime.UtcNow + ...
1
vote
1
answer
57
views
Why Task needs to use ManualResetEventSlim internally?
According to the source code of Task https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs,1483
So Task uses ManualResetEventSlim ...
-1
votes
1
answer
41
views
Parallel computation is slower than normal sequential loop
I have two functions running in parallel, however they are slower than functions with normal sequential loops. Namely, first one :
static int[] sieveWithLogs(long n, long start, int intervalSize, List&...
-1
votes
1
answer
74
views
Why ExecuteSynchronously is not the default for async await? [closed]
We know that if we uses async/await
await methodAsync();
var result = methodNonAsync()
// ...
await methodAsync() puts a item on the queue, so that a thread pool thread (says threadA) can execute ...
0
votes
0
answers
28
views
Inconsitent detection of joystick button input using SDL in C# with the use of TPL
So I made a code that will detect joystick button input in a TPL where all joysticks' inputs are detected simultaneously. Good thing is that if there's only one joystick connected, it works ...
0
votes
0
answers
43
views
Xunit Integration Test-Async method not completing when tests run in parallel
I am using .net 7 and xunit to do integration tests.
I have over 50+ test cases, each test case in a file so that my tests run in parallel. All my test methods are marked with async Task since I need ...
2
votes
2
answers
202
views
Thread.Sleep() vs Task.Delay().Wait()
Codebase was like this in a non-async¹ method:
Thread.Sleep(500);
A colleague refactored it to be like this:
Task.Delay(500).Wait();
Given the relative small delay, is really an advantage to use the ...
1
vote
1
answer
61
views
How to run BackgroundService by counter using Task?
I have a background service in my dot net core application. That will run by capacity counter.
public class WebWorkGenerator : BackgroundService
{
private const int ConsumeCapacityPerMinute = 10;
...
-1
votes
0
answers
40
views
How to run the two branches of Fibonacci series in parallel using Lazy? My code works when it is single-threaded, but not when multi-threaded
I want to be able to run CalculateFibonacci(n - 1) and CalculateFibonacci(n - 2)in parallel. I have tried putting them both in separate task, but I am getting the below error
"System....
1
vote
2
answers
59
views
How does cancellation acknowledgment work for async continuations?
The documentation for Task.IsCanceled specifies that OperationCanceledException.CancellationToken has to match the cancellation token used to start the task in order to properly acknowledge. I'm ...
2
votes
1
answer
85
views
Reducing closure overhead in Task.Run/Factory.StartNew with predefined object
This is purely for experimental purposes and/or a learning exercise. In essence, I'd like to see if I can reduce the footprint of the closure created when we use Task.Run(()=>Func<>()) by ...
2
votes
2
answers
115
views
How to pull from IObservable
Suppose there is a Subject<T> at endpoint A and an IObservable<T> on endpoint B.
Endpoint A sends exactly one object of T using OnNext() and never calls OnComplete(). I don't have a ...
1
vote
1
answer
89
views
Uncertainty about the behavior of Task.WhenAny
Say task1, task2, task3 are tasks that I start at the beginning of the function, what does
await Task.WhenAny(task1,task2,task3); return if more than one task has finished before the code reaches that ...
0
votes
0
answers
38
views
Getting error(object reference not set to an instance of an object) when using Parallel.ForEach to fetch data from Oracle database in .Net API 4.7.1 [duplicate]
This is my data access method which fetch data from Oracle database and binds it as XML response.
public IEnumerable<InquiryResponse> GetData(int storeNumber, List<RequestItem> ...
-2
votes
1
answer
68
views
Why task's status is Faulted instead of Canceled?
I was experimenting different ways of cancellations. Here you'll see 5 different approaches and there is no doubt about the first four approaches. (These are commented but kept to avoid discussion on ...
0
votes
1
answer
54
views
TPL data block with multiple inputs that can time out
Let's say i have multiple inputs (Input1, Input2 etc) of data types that can arrive at different times. If data for input 1 arrives, then i require Input2 to arrive within a certain (configurable) ...
0
votes
2
answers
54
views
TPL ActionBlock not handling messages after an exception
I've setup an ActionBlock<T> like so:
private readonly ActionBlock<PresentationListNotification> _actionBlock;
...
_actionBlock = new ActionBlock<...
0
votes
0
answers
43
views
C#: Run multiple tasks in sequential order when debugging
In my release code all scheduled tasks can be managed by the task scheduler and it can put them on any thread it likes. They have no dependency or concurrency issues to each other.
This is how I do it ...
0
votes
3
answers
278
views
Ignore task exception in ContinueWith
I want to suppress exception triggered in the task. As I recall, some time ago I used this code to make it possible:
void Main(..)
{
Task Fail()
{
throw new Exception("ex");
...
0
votes
2
answers
48
views
Process ZipArchive entries in parallel
I need to process ZipArchive entries as strings. Currently I have code like this:
using (ZipArchive archive = ZipFile.OpenRead(zipFileName))
{
foreach (ZipArchiveEntry entry in archive.Entries)
...
1
vote
1
answer
62
views
Why the catch block of AggregateException was not sufficient to handle cancellations?
Run the following code:
using static System.Console;
WriteLine("Handling cancellations and exceptions.");
CancellationTokenSource cts = new();
CancellationToken token = cts.Token;
var ...
-2
votes
1
answer
61
views
Trying to learn cancellation tokens. Not sure why this does not work
So, I'm learning Cancellation tokens and I'm trying this example. The writeline is never working even if I cancel this method from the outside.
So how this works, is the initializeAsync, if it takes ...
-1
votes
1
answer
159
views
Is there a way to run an async method as a LongRunning task?
I'm looking to run an async method as a long-running thread, as in using the TaskCreationOptions.LongRunning option. In my testing I'm considering the thread as running as a "long-running" ...
0
votes
1
answer
93
views
How to ensure different CultureInfo.CurrentCulture for calls to specific library
I have a 3rd party library that uses CultureInfo.CurrentCulture but it must be set to InvariantCulture to function properly.
My multithreaded application uses localized CultureInfo.CurrentCulture.
...
0
votes
1
answer
63
views
Task.WaitAll AggregateException handling
I've got a program processing results in batches of 100. It makes api request (one item each) and then batch processes the results.
Recently, the api I'm calling has developed scaling problems and, ...
0
votes
1
answer
374
views
Correct way for long running background task on ASP.NET Core, for CPU bound and I/O bound
In my .NET7 ASP.NET server I use this code to do some background processing for the lifetime of the application.
_ = Task.Run(async () =>
{
while (true)
{
try
{
...
1
vote
1
answer
116
views
Implementing Tasks, await and async for background work
I am new to Tasks and its associated keywords in C#. My goal is to setup a background thread/task that will continuously poll a server every n seconds. Using the .NET TPL library, is the following ...
0
votes
1
answer
90
views
Why isn't Task.WhenAll waiting until completion?
I'm running into an issue here and you might know the answer: I just couldn't figure it out still.
I'm creating a seed for a simple scenario here: adding likes to a given post.
The method signature is:...
2
votes
1
answer
123
views
How to prevent to create more threads than the available number of hardware threads?
I have the following method below that used to initialize and start log files processing by creating a different task for each file. In the Task Manager I can see this function is creating about one ...
0
votes
1
answer
66
views
.NET TPL: Why is delegate being ran like it was executed with blocking wait call?
When I'm trying to run Task.Run method with delegate which runs another task without blocking call it's being ran like my task was exectued with Wait blocking call?
Here is an example:
I'm trying to ...
0
votes
0
answers
30
views
Call method using TPL with limit of maximum 10 request [duplicate]
I have 1000 records to process pending items. So, I need to call a C# method which is in TPL (parallel mechanism) but with the max request of 10. So that I can process 10 requests at a time in a batch ...
0
votes
0
answers
85
views
Limiting number of running tasks in a loop [duplicate]
I have a situation where I would like to limit the number of concurrent running tasks. If you look into the code below..
public class TaskScheduler
{
public void Initialize()
{
var ...
1
vote
1
answer
84
views
Has ContinueWith()'s body a chance of being invoked before ContinueWith() returns the related Task?
I have a synchronized Task list populated, for monitoring purposes.
I want to progressively remove the completed tasks from the list. To do so I resolved to use Continuation tasks like so:
//remove ...
0
votes
0
answers
36
views
Using Task.Run for IO bound work to avoid updating method signatures
This method contains a bunch of Redis code, and is called in many places and is part of a deep method call stack:
public void Save()
{
Task.Run(async () =>
{
var ...
1
vote
0
answers
78
views
How to implement Stop/Cancel async operations in WinForms application when I can't pass token to async method? [duplicate]
I have asynchronious WinForms application that uses
async/await event handlers of buttons
objects with asynchronous method from another assembly that I can't modify.
I want
to disable elements ...
0
votes
1
answer
97
views
What method is most common for performing parallel operations in Orleans?
I'm planning to move some ASP.NET code that performs several I/O operations in parallel. The existing code creates a Task for each operation and then uses Task.WaitAll to wait for these to finish ...
1
vote
1
answer
50
views
Do Parallel Loops with MaxDegreesOfParallelism = 1 run on the calling thread?
The MSDN page does not really state what happens when ParallelOptions.MaxDegreesOfParallelism equals 1.
I make extensive use of the Parallel loops and I would like to debug it when it runs ...
1
vote
1
answer
133
views
Is calling interface method from within Parallel.ForEachAsync() thread safe?
Here's some code just to hopefully make clear the situation I'm talking about:
public class Processor
{
private readonly IRepository _repo;
private readonly IApiSrevice _apiService
...
1
vote
1
answer
37
views
3rd Party SDK call in Parallel.Foreach loop handling events
I'm batching up items and processing them in parallel similarly to what is shown below. I need information not returned in the task that is sent through the two eventhandlers shown below (status ...
1
vote
3
answers
150
views
Difference between Task.Run with async await and without it for parallel operation
I want to understand the difference between using Task.Run with async await and without it for parallel operation, awaiting in the end when all operations completed.
Below is the code, I see both ...
-2
votes
1
answer
85
views
async Task or async void for Main method?
Should we use async Task or async void in the Main method of C# program?
public static async Task Main(string[] args)
{
//await something
}
or
public static async void Main(string[] args)
{
//...
0
votes
0
answers
102
views
How to run parallel operations on set of files?
So I'm trying to run parallel operations on a set of files using C#.
The first operation converts the file type and stores it in a temporary folder. The second operation does some processing to the ...
-1
votes
1
answer
94
views
Producer / Consumer Problem : Facing deadlock
I employed exactly a couple of threads to produce and consume the data within the buffer.
There is only one thread for producing the data and only one thread to consume.
However, I still face deadlock ...
0
votes
0
answers
33
views
Using Task.Run() causes unexpected behavior in calling loop [duplicate]
I have the following C# code:
public List<bool> scaleActive { get; private set; }
//...
for (int i = 0; i < scaleActive.Count; i++)
{
if (scaleActive[i])
{
//...
Task....
-2
votes
2
answers
81
views
Best way to interact with I/O bound threads to produce 100 GB random data in C# using TPL [closed]
I need to produce a 100GB file with random data. I know it's all I/O intensive operation apart from a few lines that are just generating random data.
My target is to create 100 GB or 50 GB files. I ...