Deep C# - Threading,Tasks and Locking |
Written by Mike James | ||||||||
Wednesday, 22 October 2025 | ||||||||
Page 7 of 7
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 = 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 =
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. PostludeThreads 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 ArticlesWhat Is Asynchronous Programming? Managing Asynchronous Code - Callbacks, Promises & Async/Await Deep C#Buy Now From Amazon Chapter List
Extra Material <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.
Comments
or email your comment to: comments@i-programmer.info
|
||||||||
Last Updated ( Wednesday, 22 October 2025 ) |