Last active
November 25, 2015 16:54
-
-
Save henkmollema/5c1683c120d4bc5a361b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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