Skip to content

Instantly share code, notes, and snippets.

@snmslavk
Created April 22, 2016 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snmslavk/4a8479c9c98478578649690695488f39 to your computer and use it in GitHub Desktop.
Save snmslavk/4a8479c9c98478578649690695488f39 to your computer and use it in GitHub Desktop.
Different usage of Aync in C#
public class MegaClass
{
public async void StartAsync()
{
await Task.Run(() => { LongProcedure(); });
Console.WriteLine("End");
}
public void Start()
{
LongProcedure();
Console.WriteLine("End");
}
private void LongProcedure()
{
Thread.Sleep(3000);
}
public async Task MyMethodAsync()
{
int x = await LongRunningOperationAsync();
Console.WriteLine(x);
}
public async Task<int> LongRunningOperationAsync()
{
await Task.Delay(3000);
return 1;
}
public async Task<int> LongRunningOperationAsync(int _param)
{
await Task.Delay(3000);
return _param;
}
}
class Program
{
static void Main(string[] args)
{
var _c = new MegaClass();
//1 Sync
//_c.Start();
//2 Async
//c.StartAsync();
//3 Start and return task
//Task t = _c.MyMethodAsync();
//t.Wait();
//4
//Task task = new Task(_c.StartAsync);
//task.Start();
//5 GetResult <int>
//Task<int> x = _c.LongRunningOperationAsync();
//x.Wait();
//Console.WriteLine(x.Result);
//6 with param
//Task<int> x = _c.LongRunningOperationAsync(3);
//x.Wait();
//Console.WriteLine(x.Result);
Console.WriteLine("Wait");
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment