From the course: Asynchronous Programming in C#

Unlock the full course today

Join today to access over 24,800 courses taught by industry experts.

Implementing timeout cancellations

Implementing timeout cancellations - C# Tutorial

From the course: Asynchronous Programming in C#

Implementing timeout cancellations

- In this lesson, I want to show you an example of using the cancellation token source class, and cancellation tokens, to implement timeout cancellations for asynchronous methods. I've already got some code in place here that will asynchronously read the contents of a text file before printing it to the screen. I've hard coded the name of the file I'm going to read here on line three. Below that, I declare a byte array that will hold the contents of the file. I then use a try catch block to create a new file stream and read the data. The asynchronous work begins on line 11, when I call the "read async" method that exists on file stream instances. I'm currently passing it three parameters that basically instruct the method to read the entire file into the "contents" bite array. There's no code to implement cancellation here yet. Notice that I'm also awaiting the completion of the "read async" method, and then writing the…

Contents