How to do it...

  1. Create a text file and two folders to contain the log files. We will, however, only create a single log file in the BackupLog folder. Name your text file taskFile.txt and copy it to the BackupLog folder. The MainLog folder will remain empty:
  1. In our AsyncDemo class, write a method to read the log file in the folder specified by the enum value:
      private async Task<int> ReadLog(LogType logType)
{
string logFilePath = String.Empty;
if (logType == LogType.Main)
logFilePath = @"C: empLogMainLog askFile.txt";
else if (logType == LogType.Backup)
logFilePath = @"C: empLogBackupLog askFile.txt";

string enumName = Enum.GetName(typeof(LogType), (int)logType);

var bigFile = File.OpenRead(logFilePath);
var bigFileBuffer = new byte[bigFile.Length];
var readBytes = bigFile.ReadAsync(bigFileBuffer, 0,
(int)bigFile.Length);
await readBytes.ContinueWith(task =>
{
if (task.Status == TaskStatus.RanToCompletion)
Console.WriteLine($"{enumName} Log RanToCompletion");
else if (task.Status == TaskStatus.Faulted)
Console.WriteLine($"{enumName} Log Faulted");

bigFile.Dispose();
});
return await readBytes;
}
  1. Create the enum value as shown here:
      public enum LogType { Main = 0, Backup = 1 }
  1. We will then create a main ReadLogFile() method that tries to read the main log file. As we have not created the log file in the MainLog folder, the code will throw a FileNotFoundException. It will then run the asynchronous method and await it in the catch block of the ReadLogFile() method (something that was impossible in the previous versions of C#), returning the bytes read to the calling code:
      public async Task<int> ReadLogFile()
{
int returnBytes = -1;
try
{
returnBytes = await ReadLog(LogType.Main);
}
catch (Exception ex)
{
try
{
returnBytes = await ReadLog(LogType.Backup);
}
catch (Exception)
{
throw;
}
}
return returnBytes;
}
  1. If you've not done so in the previous recipe, add a button to your Windows forms application's Forms Designer. On the winformAsync Forms Designer, open Toolbox and select the Button control, which is found under the All Windows Forms node:
  1. Drag the Button control onto the Form1 designer:
  1. With the Button control selected, double-click on the control to create the click event in the code behind. Visual Studio will insert the event code for you:
      namespace winformAsync 
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

}
}
}
  1. Change the button1_Click event and add the async keyword to the click event. This is an example of a void returning an asynchronous method:
      private async void button1_Click(object sender, EventArgs e) 
{

}
  1. Next, we will write the code to create a new instance of the AsyncDemo class and attempt to read the main log file. In a real-world example, it is at this point that the code does not know that the main log file does not exist:
      private async void button1_Click(object sender, EventArgs  e) 
{
Console.WriteLine("Read backup file");
AsyncDemo oAsync = new AsyncDemo();
int readResult = await oAsync.ReadLogFile();
Console.WriteLine("Bytes read = " + readResult);
}
  1. Running your application will display the Windows forms application:
  1. Before clicking on the button1 button, ensure that the Output window is visible:
  1. From the View menu, click on the Output menu item or type Ctrl + W + O to display the Output window. This will allow us to see the Console.Writeline() outputs that we added to the code in the AsyncDemo class and in the Windows application.
  2. To simulate a file not found exception, we deleted the file from the MainLog folder. You will see that the exception is thrown, and the catch block runs the code to read the backup log file instead:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.74.211