Book Image

C# Programming Cookbook

By : Dirk Strauss
Book Image

C# Programming Cookbook

By: Dirk Strauss

Overview of this book

During your application development workflow, there is always a moment when you need to get out of a tight spot. Through a recipe-based approach, this book will help you overcome common programming problems and get your applications ready to face the modern world. We start with C# 6, giving you hands-on experience with the new language features. Next, we work through the tasks that you perform on a daily basis such as working with strings, generics, and lots more. Gradually, we move on to more advanced topics such as the concept of object-oriented programming, asynchronous programming, reactive extensions, and code contracts. You will learn responsive high performance programming in C# and how to create applications with Azure. Next, we will review the choices available when choosing a source control solution. At the end of the book, we will show you how to create secure and robust code, and will help you ramp up your skills when using the new version of C# 6 and Visual Studio
Table of Contents (21 chapters)
C# Programming Cookbook
Credits
About the Author
Acknowledgements
About the Reviewer
www.PacktPub.com
Preface
Index

Handling tasks in asynchronous programming


Task-Based Asynchronous Pattern (TAP) is now the recommended method to create asynchronous code. It executes asynchronously on a thread from the thread pool and does not execute synchronously on the main thread of your application. It allows us to check the task's state by calling the Status property.

Getting ready

We will create a task to read a very large text file. This will be accomplished using an asynchronous Task.

How to do it…

  1. Create a large text file (we called ours taskFile.txt) and place it in your C:\temp folder:

  2. In the AsyncDemo class, create a method called ReadBigFile() that returns a Task<TResult> type, which will be used to return an integer of bytes read from our big text file:

    public Task<int> ReadBigFile()
    {    
    
    }
  3. Add the following code to open and read the file bytes. You will see that we are using the ReadAsync() method that asynchronously reads a sequence of bytes from the stream and advances the position in that stream...