Deep C# - Threading,Tasks and Locking
Written by Mike James   
Wednesday, 22 October 2025
Article Index
Deep C# - Threading,Tasks and Locking
Starting A Thread
Ensuring Thread Safety
Exclusion Using Locking
Deadlock
Background Worker
Task Parameters

If you want to pass parameters to the Task you can use the alternative constructor and an object:

Task(Action,object)
Task<Tresult>(Func<Tresult>,object)

The object is passed to the Task and the only problem is how to pack the parameters into the object. One of the simplest but by no means the only scheme is to use a value tuple and casting.

For example, function A in the example can be rewritten to allow the start and stop values for the loop to be specified:

public void A(object pars)
{
        (int start,int stop) args =
((int start, int stop)) pars; for (int i = args.start; i < args.stop; i++) { Monitor.Enter(MyCountLock); count++; Monitor.Exit(MyCountLock); } }

Notice that we cast the object to a named value tuple and then use its fields. With this definition we a can start a Task with parameters using:

Task T1 = new Task(A, (0, 10000000));
T1.Start();

You can use the same method to pass any number of parameters of any type.

Getting a result back is even easier. All you have to do is use:

Task<Tresult>(Func<Tresult>)

or:

Task<Tresult>(Func<Tresult>,object)

if you also want to pass in parameters.

For example, to make function A return a result we could use:

public int A(object pars)
{
    	(int start,int stop) args =
((int start, int stop)) pars ; for (int i = args.start; i < args.stop; i++) { Monitor.Enter(MyCountLock); count++; Monitor.Exit(MyCountLock); } return count; }

 

To make use of this we use:

Task<int> T1 = new Task<int>(A, (0, 10000000));
T1.Start();
textBox1.Text = T1.Result.ToString();

There are many advantages of using the Task class, but it is worth remembering that it is just a light wrapper for a thread. What this means is that you can use all of the locking and similar mechanisms already introduced.

There are lots of other methods and properties that are worth investigating and unless you have a good reason you should use Task in preference to a raw thread. In particular, a Task is cancelable and can therefore serve as the basis for other more abstract features such as async and await and the parallel for.

Postlude

Threads are the key to keeping an application’s UI responsive and they are also the way to make servers able to deal with multiple clients at the same time. They are important but difficult to get right. You can use raw threads in C#, but task objects are so much easier and safer. Even so you have to be on the lookout for the unique problems that occur when you try to share resources between active threads. In all cases, simple is better.

Related Articles

What Is Asynchronous Programming?

Managing Asynchronous Code - Callbacks, Promises & Async/Await

Deep C#

 Buy Now From Amazon

DeepCsharp360

 Chapter List

  1. Why C#?
    I Strong Typing & Type Safety
  2. Strong Typing
       Extract 
    Why Strong Typing
  3. Value & Reference
       Extract
    Value And Reference
  4. Structs & Classes
       Extract
    Structs & Classes 
  5. Inheritance
      
    Extract
    Inheritance
  6. Interfaces & Multiple Inheritance
      
    Extract Interface
  7. Controlling Inheritance
    II Casting & Generics
  8. Casting - The Escape From Strong Typing
      
    Extract Casting I
  9. Generics
  10. Advanced Generics
  11. Anonymous & Dynamic
    Typing
    III Functions
  12. Delegates 
  13. Multicast Delegates
  14. Anonymous Methods, Lambdas & Closures
    IV Async
  15. Threading,Tasks and Locking ***NEW!
  16. The Invoke Pattern
  17. Async Await
  18. The Parallel For
    V Data - LINQ, XML & Regular Expressions
  19. The LINQ Principle
  20. XML
  21. LINQ To XML
  22. Regular Expressions
    VI Unsafe & Interop
  23. Interop
  24. COM
  25. Custom Attributes
  26. Bit Manipulation
  27. Advanced Structs
  28. Pointers 

Extra Material
Passing Parameters ***NEW!

 <ASIN:B09FTLPTP9>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner


Seymour Cray - Born This Day In 1925
28/09/2025

Today we celebrate the 100th anniversary of the birth of Seymour Cray, regarded as the father of the supercomputer. One of the most original computer designers the world has ever seen his Cray 1 remai [ ... ]



Meet Reo.Dev, the Developer Intent Platform
08/10/2025

Selling software to engineering teams has always been a challenge for developer tools companies. Formal sales cycles often lag months behind a developer’s initial, silent adoption of a tool. To addr [ ... ]


More News

pico book

 

Comments




or email your comment to: comments@i-programmer.info

 



Last Updated ( Wednesday, 22 October 2025 )