Skip to content

Instantly share code, notes, and snippets.

@henkmollema
Last active November 25, 2015 16:54
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 henkmollema/5c1683c120d4bc5a361b to your computer and use it in GitHub Desktop.
Save henkmollema/5c1683c120d4bc5a361b to your computer and use it in GitHub Desktop.
public class ClassA
{
public Task TheTask;
public string Result;
public ClassA()
{
TheTask = SomeLongMethod();
}
private async Task SomeLongMethod()
{
// Run the CPU-blocking method on another thread and wait for the result
// This does not block the main thread.
Result = await Task.Run(() => Test());
}
public string Test()
{
// Do some CPU-blocking work
Thread.Sleep(1000);
return DateTime.Now.ToString("HH:mm:ss.ffff");
}
}
public class ClassB
{
public string Test(ClassA a)
{
// Simulate the time between ClassA is instantiated
// and the result of the task is actually needed.
Thread.Sleep(1000);
// Wait the remaining time of the task.
a.TheTask.Wait();
// Use the result of the task stored in the other field.
return a.Result;
}
}
public class Program
{
private ClassA a;
public Program()
{
a = new ClassA();
}
public async Task Main(string[] args)
{
var b = new ClassB();
string res = b.Test(a);
Console.WriteLine(res);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment