using System.Windows.Forms;
using System.Threading; //Added
namespace Asynch_Programming_With_Async_Await_Ex2
{
public partial class Form1 : Form
{
Random rand = new Random();
public Form1()
{
InitializeComponent();
}
private void btnTestIftheUIisLocked_Click(object sender, EventArgs e)
{
MessageBox.Show("Testing if the UI is locked");
}
private void btnwithriginalMethodLockedUI_Click(object sender, EventArgs e)
{
double result = DisplaySumOfRandomValues();
richTextBox1.AppendText("Sum of Random Values: " + result);
}
//original method that lock UI
private double DisplaySumOfRandomValues()
{
double sum = 0;
for (int i = 1; i < 1000; i++)
{
sum += rand.Next(1000000, 2000000);
Thread.Sleep(1); //simulating long running method.
}
return sum;
}
private async void btnRunMethodWithoutLockingUI_Click(object sender, EventArgs e)
{
double result = await GetSumOfRandomValuesAsync();
richTextBox1.AppendText("Get Sum of Random Values: " + result);
}
private async Task<double> GetSumOfRandomValuesAsync()
{
//If nothing to return, the await task can be written as follow,
//await Task<double>.Factory.StartNew(() =>
Task<double> task = Task<double>.Factory.StartNew(() =>
{
double sum = 0;
for (int i = 1; i < 1000; i++)
{
sum += rand.Next(1000000, 2000000);
Thread.Sleep(1); //simulating long running method.
}
return sum;
});
//Since the task.Result blocks/waits until the sum is returned from the task
//you should await the task so that the method returns to the caller
//at this point and comes back to finish the rest of the code when the task completes
await task;
return task.Result; //calling result from a task
}
//method for lab
private long Fibonacci(long n)
{
if (n == 0) return 0;
if (n == 1) return 1;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
}
//Lab Assingment due Wed 3/4
//New project
//given the fibonacci series method
//define an asynchronous method that takes an input n and returns its Fibonnacci value
//Call this method (from a button click) and display its return value.
//The UI thread should not lock up.
////www.dotnetperls.com/async
///www.codeproject.com/Tips/591586/Asynchronous-Programming-in-Csharp-using-async
////stackoverflow.com/questions/16728338/how-can-i-run-both-of-these-methods-at-the-same-time-in-net-4-5
///msdn.microsoft.com/en-us/library/vstudio/hh191443(v=vs.110).aspx#BKMK_HowtoWriteanAsyncMethod
///blog.stephencleary.com/2012/02/async-and-await.html

No comments:
Post a Comment