All Questions
Tagged with .net-4.5 multithreading
101
questions
103
votes
3
answers
83k
views
Proper way to implement a never ending task. (Timers vs Task)
So, my app needs to perform an action almost continuously (with a pause of 10 seconds or so between each run) for as long as the app is running or a cancellation is requested. The work it needs to do ...
50
votes
6
answers
32k
views
Task.Yield - real usages?
I've been reading about Task.Yield , And as a Javascript developer I can tell that's it's job is exactly the same as setTimeout(function (){...},0); in terms of letting the main single thread deal ...
28
votes
4
answers
17k
views
c# .net 4.5 async / multithread?
I'm writing a C# console application that scrapes data from web pages.
This application will go to about 8000 web pages and scrape data(same format of data on each page).
I have it working right now ...
23
votes
2
answers
6k
views
Why does MemoryCache throw NullReferenceException
Update
See updates below, issue is fixed the moment you install .Net 4.6.
I want to implement something within the UpdateCallback of CacheItemPolicy.
If I do so and test my code running multiple ...
22
votes
4
answers
19k
views
Why is await async so slow?
I finally got VS2012 and got a simple demo up and working to check out the potential performance boost of async and await, but to my dismay it is slower! Its possible I'm doing something wrong, but ...
17
votes
1
answer
14k
views
How many threads Parallel.For(Foreach) will create? Default MaxDegreeOfParallelism?
I want to know, how many threads will be used when I run Parallel.For/ForEach loop.
I found, that it can be changed by MaxDegreeOfParallelism option.
MaxDegreeOfParallelism help on MSDN says (link):
...
15
votes
2
answers
9k
views
Does Task.Delay start a new thread?
The following code should (at least in my opinion) create 100 Tasks, which are all waiting in parallel (that's the point about concurrency, right :D ?) and finish almost at the same time. I guess for ...
13
votes
5
answers
10k
views
SemaphoreSlim with dynamic maxCount
I'm facing a problem where I need to limit the number of calls to another web server. It will vary because the server is shared and maybe it could have more or less capacity.
I was thinking about ...
12
votes
4
answers
2k
views
What .NET 4.5 (or earlier) higher-level constructs make Threading easier?
Delegates are a few of the objects that make threading easier in .NET reference. They can be used to asynchronously invoke a method. What other objects exist in framework 4.5 (or earlier) that make ...
10
votes
2
answers
1k
views
Is Volatile.Read / Volatile.Write for "double" atomic?
MSDN states that:
Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, need not be atomic.
C# 7.0 draft specification - Variables - 9.6 ...
9
votes
3
answers
3k
views
When exactly does .NET Monitor go to kernel-mode?
I would like to compile a list of all possible conditions making Monitor go to kernel-mode or use a kernel sync object.
The sync block has a field to reference the kernel object. Hence I deducted that ...
9
votes
2
answers
2k
views
Thread parameters being changed
When starting multiple threads, the id parameter I'm parsing is sometimes wrong. Here is my startup:
for (int i = 0; i < _threadCount; i++)
{
Thread thread = new Thread(() => WorkerThread(i)...
9
votes
3
answers
1k
views
Volatile fields: How can I actually get the latest written value to a field?
Considering the following example:
private int sharedState = 0;
private void FirstThread() {
Volatile.Write(ref sharedState, 1);
}
private void SecondThread() {
int sharedStateSnapshot = ...
9
votes
1
answer
3k
views
Customizing ActionBlock<T>
I want to implement a prioritised ActionBlock<T>. So that i can Conditionally give priority to some TInput items by using a Predicate<T>.
I read Parallel Extensions Extras Samples and ...
8
votes
3
answers
1k
views
C# Concurrency - Preferred approach to long running tasks
When there needs to be an I/O listener running throughout an applications lifetime, what concurrency model is preferred with C# 5.0 running on the 4.5 framework?
I've settled on the idea that a ...
7
votes
2
answers
2k
views
Multi-Threading a Large C# Application Using async/await
All, I have been given the job to multi-thread a large C# application. To do this I have chosen to go use async/await. I am well aware of the use of IProgress<T> to report progress to the UI (...
5
votes
3
answers
600
views
Is Parallel.ForEach obsolete. old, out of fashion?
Good day,
Parallel execution can be achieved through multiple ways. From strictly manual "multithreading" to using various "helpers" created by Microsoft. One of those helpers is the Parallel class. ...
5
votes
1
answer
2k
views
Running external processes asynchronously in a windows service
I am writing a program that moves csv files from a "queue" folder to a "processing" folder, then a third party process called import.exe is launched taking the csv file path as an argument. Import.exe ...
5
votes
1
answer
977
views
What has changed in the memory model in .NET 4.5?
I just read this puzzling line in Peter Richtie blog and I need help to understand the meaning Prior to .NET 4.5 you really programmed to the .NET memory model : http://msmvps.com/blogs/peterritchie/...
4
votes
3
answers
2k
views
Do each new System.Threading.Tasks.Task() creates a new thread?
I was just trying to figure out as I am using Task object for to have my time taking operation runs in a separate channel. But I wonder do Task(()=>{...}) is it similar to create new Thread(new ...
4
votes
3
answers
147
views
EmptyEnumerable<T>.Instance assignment and multi-threading design
This is more of a design question I guess than an actual bug or a rant. I wonder what people think about the following behavior:
In .NET, when you want to represent an empty IEnumerable efficiently ...
4
votes
2
answers
999
views
Why do my threads seemingly take up less than 1MB of memory?
I'm trying to get a better grasp of the .NET threading model. I've heard and read multiple times (most recently when watching this video: AppFabric.tv - Threading with Jeff Richter) that .NET threads ...
4
votes
1
answer
379
views
What is the stack size of a BackgroundWorker DoWork Thread? Is there way to change it?
I know for a C# main program the stack size 1 MB (32-bit and any) or 4 MB (64-bit), see Why is stack size in C# exactly 1 MB?
What is the default stack size of the BackgroundWorker DoWork thread?
Is ...
4
votes
0
answers
567
views
QueueBackgroundWorkItem throwing ThreadAbortException
I am trying to queue a background worker from inside a WebAPI call:
public string TestThreadAbortException()
{
InitToolkit(DebugLevel.ERROR, 11937, true); // Initialize Logger, DB etc....
4
votes
1
answer
384
views
Handle leak when exception is thrown inside task
I'm trying to understand a very strange handle leak that is occurring in an application.
I've managed to isolate the problem in the following code:
using System;
using System.Collections.Generic;
...
3
votes
2
answers
3k
views
Writing to a file from multiple threads without lock
I need to write data buffer by buffer in to a file from different threads. To avoid locking I am writing into different files, say 'file_1','file_2' and at last merges all these files to 'file'. Is ...
3
votes
2
answers
5k
views
How to implement Command Pattern with async/await
i'm currently upgrading some existing code for use by windows universal and am struggling to convert a command pattern to work with the new async/await functionality.
I have a command scheduler class ...
3
votes
4
answers
3k
views
Waiting for something to happen - asynchronous or synchronous model?
I have this method WaitForReaderArrival which is like below: (Runs all the time waiting for a reader to arrive)
public void WaitForReaderArrival()
{
do
{
...
3
votes
2
answers
145
views
Do children Forms run on the same thread of the main Form by default?
If I create a child Form will it operate on the same thread as it's parent Form?
3
votes
1
answer
1k
views
Wait for IProgress Report Method to Return
I am updating my UI via IProgress and the Report method. I do something like
IProgress<ProgressInfo> p = new Progress<ProgressInfo>(ReportProgress);
Task task = Task.Factory.StartNew(() =...
3
votes
1
answer
2k
views
ConcurrentBag vs Custom Thread Safe List
I have a .NET 4.5 Single Instance WCF service which maintains a collection of items in a list which will have simultaneous concurrent readers and writers, but with far more readers than writers.
I am ...
3
votes
1
answer
1k
views
Correct Way to Throw and Catch Exceptions using async/await
All, please take the following code:
Task<bool> generateStageAsyncTask = null;
generateStageAsyncTask = Task.Factory.StartNew<bool>(() =>
{
return GenerateStage(ref workbook);
}, ...
3
votes
1
answer
597
views
Monitoring File lock release with a timeout in multithreading context
I am using FileSystemWatcher to notify me whenever a file arrives in a folder of my system.
Sometimes, they arrive with a lock (by some other program)
I want to perform something like below:
If ...
3
votes
0
answers
304
views
Will use of a kernel object in C# flush CPU cache?
If I have a code similar to this:
ManualResetEvent me = new ManualResetEvent(false);
. . .
int a = 10;
. . .
me.WaitOne();
. . .
assume a is in the CPU cache after the assignment, will call to ...
2
votes
2
answers
98
views
Clarification on tasks in .net
I'm trying to understand tasks in .net from what I understand is that they are better than threads because they represent work that needs to get done and when there is a idle thread it just gets ...
2
votes
2
answers
303
views
Dictionary of lock object in order to reduce latency in C#?
When an online user send a message to a offline user , I keep those messages in a ConcurrentDictionary . each user is running/spinning in its own Task(thread).
public static ConcurrentDictionary<...
2
votes
2
answers
6k
views
Default timeout for Task.WaitAll()
What is the default timeout for Task.WaitAll? Is it infinite?
Is Task.WaitAll(stuff.AsyncMethod()); equal to Task.WaitAll(new Task[] { stuff.AsyncMethod() }, -1); ?
I have tried Googling and chacked ...
2
votes
2
answers
669
views
How to put many different thread to wait() and be able to awake them all with signalAll()?
I've studied that in concurrent programming there's something called "event semaphore" that works like this:
Let's say "sem" is the event semaphore object.
Threads executing sem.Wait() are suspended ...
2
votes
1
answer
1k
views
Syncronization of async EF Tasks
I am working on an Application to processes Company resources. We have a MS SQL Database and are working with EntityFramework 6.1.3 and .Net4.5.
Now DbContext has async methods for example
protected ...
2
votes
1
answer
428
views
Sharing object context Tasks
I have a list lstSubscriptionRequests on which indivisual items i am doing some sort of processing asynchronously. Then after All items are processed i have to return the updated list items. My ...
2
votes
1
answer
166
views
What is the best way to determine max amount of threads for C# IO operations based on the system's hard drive?
I've got a tool that will run multiple threads at once that will perform a simple IO operation. The question I have is; What is the best way to determine the max amount of possible threads, based on ...
2
votes
2
answers
5k
views
What is a best approach for multithreading on SerialPort
as I am new in multithreaded application I would like to have some advice from more experienced people before starting to write the code...
I need to queue data received on serial port in serial port ...
2
votes
2
answers
956
views
Producer/Consumer pattern in .NET
I have a tcp WCF service that is meant to calculate certain prices and put them into a queue for the client to pick up and to display.
The first thing that came to my mind was the Producer/Consumer ...
2
votes
1
answer
287
views
Manage sync calls in async method .net 4.5
I have a question regarding sync call inside an async method.
I have 5 I/O calls in one async method. 3 of them have async api that I can use but 2 of them are sync (request for web service without ...
2
votes
1
answer
249
views
C# External library using static members preventing multithreading
I am using a library that was created to perform a simulation based on input data, with a single entry point, something like Run(Data data).
However unfortunately the library internally stores values ...
2
votes
0
answers
1k
views
QueueBackgroundWorkItem CancellationToken not working as expected
I have a process set up to execute on background thread. I'm trying to make sure we handle the IIS process shutting down correctly but the CancellationToken doesn't seem to be working. For testing, I ...
1
vote
1
answer
1k
views
Multi-core JIT in multithreaded application
I would like to know about how ProfileOptimization (also known as Multi-core JIT) works in multi-threaded application.
Documentation says that ProfileOptimization tracks and records methods that are ...
1
vote
3
answers
97
views
Events, Action in C# - in a threaded context
I am calling a method "Foo(object s, Action action)" inside a library.
Since, the function is itself involves some amount of execution time, i use CountDownEvents'
to notify me when the function has ...
1
vote
3
answers
750
views
How to multithread long going task in C#
I have a problem. I have application, that generate pdf with reporting services. It works fine, but it need about 20-60 sec. to generate one pdf. This time is result of bug inside the reporting ...
1
vote
2
answers
3k
views
Using Parallel.ForEach<T> to add to a new List<T>
What is the best way to use parallelization such as with Parallel.ForEach so that I can rapidly iterate a collection and add items to a new List without violating thread safety but using the ...