Reader small image

You're reading from  Parallel Programming and Concurrency with C# 10 and .NET 6

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781803243672
Edition1st Edition
Right arrow
Author (1)
Alvin Ashcraft
Alvin Ashcraft
author image
Alvin Ashcraft

Alvin Ashcraft is a software engineer and developer community champion with over 25 years of experience in software development. Working primarily with Microsoft Windows, web, and cloud technologies, his career has focused primarily on the healthcare industry. He has been awarded as a Microsoft MVP 11 times, most recently as a Windows Dev MVP. Alvin works in the Philadelphia area for Allscripts, a global healthcare software company, as a principal software engineer. He is also a board member of the TechBash Foundation, where he helps organize the annual TechBash developer conference. He has previously worked for companies such as Oracle, Genzeon, CSC, and ITG Pathfinders. Originally from the Allentown, PA area, Alvin currently resides in West Grove, PA with his wife and three daughters.
Read more about Alvin Ashcraft

Right arrow

Chapter 4: User Interface Responsiveness and Threading

One of the main reasons to introduce threading concepts to a project is the desire to keep an application responsive to user input. Accessing data through services, a database, or the filesystem can introduce delays, and the user interface (UI) should remain responsive. The real-world examples in this chapter will provide valuable options for ensuring UI responsiveness in your .NET client applications.

In this chapter, we will do the following:

  • Leveraging background threads
  • Using the thread pool
  • Updating the UI thread without exceptions

By the end of this chapter, you will understand how to take advantage of parallelism and concurrency to keep your client applications responsive and performant.

Technical requirements

To follow along with the examples in this chapter, the following software is recommended for Windows users:

  • Visual Studio 2022 version 17.0 or later
  • .NET 6

While these are recommended, if you have .NET 6 installed, you can use your preferred editor. For example, Visual Studio 2022 for Mac on macOS 10.13 or later, JetBrains Rider, or Visual Studio Code will work just as well.

All the code examples for this chapter can be found on GitHub at https://github.com/PacktPublishing/Parallel-Programming-and-Concurrency-with-C-sharp-10-and-.NET-6/tree/main/chapter04.

Let’s get started by discussing how background threads can be used to perform non-critical tasks without impacting UI performance.

Leveraging background threads

In Chapter 1, we learned how to create background threads and discussed some of their uses. Background threads have a lower priority than the primary thread of the process and other thread pool threads. In addition, active background threads will not prevent the user or the system from terminating the application.

This means that background threads are perfect for tasks such as the following:

  • Writing log and analytics data
  • Monitoring network or filesystem resources
  • Reading data into the application

Do not use background threads for critical application operations such as the following:

  • Saving application state
  • Performing database transactions
  • Application data processing

A good rule to follow when deciding whether some work can be processed by a background thread is to ask yourself whether abruptly interrupting the work to close the application would risk the data integrity of the system. So, how do you know...

Using the thread pool

There are other ways to use ThreadPool threads in a .NET application. Let’s discuss a situation where you want to accomplish the same result that was achieved with async and await in the previous example, but the methods to fetch the order data are not marked as async. One option is to update the methods to be async. If that code is not within your control to change, you have some other options available.

The ThreadPool class has a method called QueueUserWorkItem. This method accepts a method to call and queues it for execution on the thread pool. We could use it with our project like this:

ThreadPool.QueueUserWorkItem(GetCurrentOrders);

There are a few problems with using this method. The primary issue is that there is no return value to get the list of orders from the method call. You could work around this issue with some wrapper methods that update a shared thread-safe collection such as the BlockingCollection. That isn’t a great design...

Updating the UI thread without exceptions

When working with managed threading in .NET applications, there are many pitfalls that developers must learn to avoid. One of the common mistakes developers make is writing code that updates a UI control in a Windows application from a non-UI thread. This kind of error will not be detected by the compiler. Developers will receive a runtime error indicating that a control created on the main thread cannot be modified on another thread.

So, how do you avoid these runtime errors? The best way to avoid them is by not updating UI controls from background threads at all. WPF helps avoid the problem with the MVVM pattern and data binding. Binding updates are automatically marshaled to the UI thread by .NET. You can safely update properties in your ViewModel classes from a background thread without causing errors at runtime.

If you are updating UI controls directly in your code, either in a WinForms application or in the code-behind file of a...

Summary

In this chapter, we learned some useful techniques for improving client application performance. We started by exploring some different uses of async and await in the ViewModel of a WPF application. In that project, we saw that awaiting Task.WhenAll does not block the main thread, which keeps the UI responsive to user input. We discussed how Task.Run and Task.Factory.StartNew can be used to call synchronous code from asynchronous code, making it easier to introduce managed threading to existing applications. We finished up the chapter by learning some techniques to update the UI thread from other threads without causing exceptions at runtime.

You should be feeling more comfortable using async, await, and the TPL in your code after reading this chapter. Try taking what you have learned here and start adding some async code to your own client applications. For additional reading on async and await, you can check out this C# article on Microsoft Docs: https://docs.microsoft...

Questions

  1. What type should every async method return?
  2. Which method can be used to await multiple tasks?
  3. Which method to start a new task accepts TaskDispatcher as one of the parameters?
  4. When calling an async method, what type of thread will execute the task?
  5. What method should be used in a WPF application when updating a user control from a background thread?
  6. Which method should be used on a WinForms control to execute an action on the main thread but not wait for the method to complete?
  7. In WinForms, how can you check whether calling Invoke is necessary?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Parallel Programming and Concurrency with C# 10 and .NET 6
Published in: Aug 2022Publisher: PacktISBN-13: 9781803243672
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Alvin Ashcraft

Alvin Ashcraft is a software engineer and developer community champion with over 25 years of experience in software development. Working primarily with Microsoft Windows, web, and cloud technologies, his career has focused primarily on the healthcare industry. He has been awarded as a Microsoft MVP 11 times, most recently as a Windows Dev MVP. Alvin works in the Philadelphia area for Allscripts, a global healthcare software company, as a principal software engineer. He is also a board member of the TechBash Foundation, where he helps organize the annual TechBash developer conference. He has previously worked for companies such as Oracle, Genzeon, CSC, and ITG Pathfinders. Originally from the Allentown, PA area, Alvin currently resides in West Grove, PA with his wife and three daughters.
Read more about Alvin Ashcraft