SlideShare a Scribd company logo
1 of 12
Download to read offline
Pragmatic Multithreading
in .Net
Lessons from coupe of project.
Overview of the First Project
Objective: unattended process for a customer
offering PoS backup service to their clients.
Multithreading Challenge: with number of
options available in .Net - which one suits my
needs with minimal implementation effort and
flexible enough settings?
Decision: combination of Parallel.Invoke to
controll max number of threads and
IAsyncResult to control thread timeout.
Solution Overview
Processing Flow
Options for Parallelism in .Net
The best article I came across from Microsoft
Thread - tried and true, but feels antiquated.
Task and Action - seems to be great option for
iterative processing where a loop-cycle can check
for cancellation token.
Task.Factory and Parallel - powerful for spreading
the load between threads and with somewhat
overwhelming options.
PLINQ - great simplicity, not so much for control
over number of threads and/or for thread timeout.
IAsyncResult - elegant timeout support.
Control Number of Threads
The most elegant approach I found to control
number of threads:
System.Threading.Tasks.Parallel.Invoke
(
new System.Threading.Tasks.ParallelOptions()
{
//Config settings for the application
MaxDegreeOfParallelism = configuration.MaxThreads,
},
processFileActions.ToArray() //List<Action>
);
Adopted from:
http://stackoverflow.com/questions/2898609/system-threading-tasks-limit-the-
number-of-concurrent-tasks
Control Thread Timeout (void)
The most elegant approach I found to control
thread timeout (without aborting thread):
Thread threadToKill = null;
Action wrappedAction = () => {
threadToKill = Thread.CurrentThread;
action();};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) {
wrappedAction.EndInvoke(result);}
else { threadToKill.Abort();
throw new TimeoutException();}
Adopted from:
http://stackoverflow.com/questions/299198/implement-c-sharp-generic-timeout
Control Thread Timeout (<T>)
In case thread needs to return data back to
caller:
Task<T> task = Task.Factory.StartNew<T>(operation);
task.Wait(timeoutMilliseconds);
if (!task.IsCompleted)
{
throw new TimeoutException();
}
else
{
return task.Result;
}
A concurrency hiccup..
I am using NLog for tracing and some log entry
never got recorded
Assuming concurrency is the issue - how to
solve?
Lock { } is a sure bottleneck. System.Thread.
Monitor seems to work great:
private static System.Lazy<object> syncRoot =
new Lazy<object>(() => { return new object(); });
if (System.Threading.Monitor.TryEnter(syncRoot, 100))
Logger._nLogger.Value.Log(level, message);
Adopted from:
http://stackoverflow.com/questions/5565395/better-solution-to-multithreading-riddle
Overview of the Second Project
Objective: unattended process for Bell.ca web
site to purge unused online profiles.
Multithreading Challenge: with tens of
millions of records of raw data - where to use
multithreading and where not to, how to avoid
killing the Sql Server database, the Smtp, or
the sFtp?
Decision: combination of PLinq.ForAll() and
process time-to-live.
Control Number of Threads
The easiest approach I found to control number
of threads with PLinq:
candidates
.AsParallel()
.WithDegreeOfParallelism(10)
.ForAll(c =>ProcessCandidate(c));
Where candidates is list of EntityFramework
objects and ProcessCandidate is a method to
send an email to each customer.
What to/what not to Multithread?
Do:
● sFtp file download and upload as slow but
not taxing process on local machine
resources
● File decompress and compress as multi-core
CPU's are readily available.
● Massive data inserts into Sql Server using
BCP Utility as database is on another
machine and LAN is fast.
Do not:
● Email Notification - to avoid race condition

More Related Content

Viewers also liked

Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 
Exploring the Next Generation Digital Learning Environment with Tsugi
Exploring the Next Generation Digital Learning Environment with TsugiExploring the Next Generation Digital Learning Environment with Tsugi
Exploring the Next Generation Digital Learning Environment with TsugiCharles Severance
 
Threading in c#
Threading in c#Threading in c#
Threading in c#gohsiauken
 

Viewers also liked (6)

Multithreading Design Patterns
Multithreading Design PatternsMultithreading Design Patterns
Multithreading Design Patterns
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
Delegates and events
Delegates and events   Delegates and events
Delegates and events
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Exploring the Next Generation Digital Learning Environment with Tsugi
Exploring the Next Generation Digital Learning Environment with TsugiExploring the Next Generation Digital Learning Environment with Tsugi
Exploring the Next Generation Digital Learning Environment with Tsugi
 
Threading in c#
Threading in c#Threading in c#
Threading in c#
 

Recently uploaded

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Pragmatic Multithreading in .Net

  • 2. Overview of the First Project Objective: unattended process for a customer offering PoS backup service to their clients. Multithreading Challenge: with number of options available in .Net - which one suits my needs with minimal implementation effort and flexible enough settings? Decision: combination of Parallel.Invoke to controll max number of threads and IAsyncResult to control thread timeout.
  • 5. Options for Parallelism in .Net The best article I came across from Microsoft Thread - tried and true, but feels antiquated. Task and Action - seems to be great option for iterative processing where a loop-cycle can check for cancellation token. Task.Factory and Parallel - powerful for spreading the load between threads and with somewhat overwhelming options. PLINQ - great simplicity, not so much for control over number of threads and/or for thread timeout. IAsyncResult - elegant timeout support.
  • 6. Control Number of Threads The most elegant approach I found to control number of threads: System.Threading.Tasks.Parallel.Invoke ( new System.Threading.Tasks.ParallelOptions() { //Config settings for the application MaxDegreeOfParallelism = configuration.MaxThreads, }, processFileActions.ToArray() //List<Action> ); Adopted from: http://stackoverflow.com/questions/2898609/system-threading-tasks-limit-the- number-of-concurrent-tasks
  • 7. Control Thread Timeout (void) The most elegant approach I found to control thread timeout (without aborting thread): Thread threadToKill = null; Action wrappedAction = () => { threadToKill = Thread.CurrentThread; action();}; IAsyncResult result = wrappedAction.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { wrappedAction.EndInvoke(result);} else { threadToKill.Abort(); throw new TimeoutException();} Adopted from: http://stackoverflow.com/questions/299198/implement-c-sharp-generic-timeout
  • 8. Control Thread Timeout (<T>) In case thread needs to return data back to caller: Task<T> task = Task.Factory.StartNew<T>(operation); task.Wait(timeoutMilliseconds); if (!task.IsCompleted) { throw new TimeoutException(); } else { return task.Result; }
  • 9. A concurrency hiccup.. I am using NLog for tracing and some log entry never got recorded Assuming concurrency is the issue - how to solve? Lock { } is a sure bottleneck. System.Thread. Monitor seems to work great: private static System.Lazy<object> syncRoot = new Lazy<object>(() => { return new object(); }); if (System.Threading.Monitor.TryEnter(syncRoot, 100)) Logger._nLogger.Value.Log(level, message); Adopted from: http://stackoverflow.com/questions/5565395/better-solution-to-multithreading-riddle
  • 10. Overview of the Second Project Objective: unattended process for Bell.ca web site to purge unused online profiles. Multithreading Challenge: with tens of millions of records of raw data - where to use multithreading and where not to, how to avoid killing the Sql Server database, the Smtp, or the sFtp? Decision: combination of PLinq.ForAll() and process time-to-live.
  • 11. Control Number of Threads The easiest approach I found to control number of threads with PLinq: candidates .AsParallel() .WithDegreeOfParallelism(10) .ForAll(c =>ProcessCandidate(c)); Where candidates is list of EntityFramework objects and ProcessCandidate is a method to send an email to each customer.
  • 12. What to/what not to Multithread? Do: ● sFtp file download and upload as slow but not taxing process on local machine resources ● File decompress and compress as multi-core CPU's are readily available. ● Massive data inserts into Sql Server using BCP Utility as database is on another machine and LAN is fast. Do not: ● Email Notification - to avoid race condition