Skip to content

Instantly share code, notes, and snippets.

@seanfisher
Last active April 3, 2017 16:45
Show Gist options
  • Save seanfisher/cc34a3c41560728dfee2d0c00ca186ae to your computer and use it in GitHub Desktop.
Save seanfisher/cc34a3c41560728dfee2d0c00ca186ae to your computer and use it in GitHub Desktop.
Does Changing a Shared Awaited Task Affect Things Already Awaiting It
using System;
using System.Threading.Tasks;
namespace AwaitTest
{
public class Program
{
private Task<int> _sharedTask;
public static void Main(string[] args)
{
var program = new Program();
program.Run().Wait();
// Prints:
// Result from Thread2: 2
// Result from Thread1: 1
}
public async Task Run()
{
_sharedTask = Print1();
var thread1 = Task.Run(Thread1);
var thread2 = Task.Run(Thread2);
await Task.WhenAll(thread1, thread2);
}
public async Task Thread1()
{
var result1 = await _sharedTask;
Console.WriteLine($"Result from Thread1: {result1}");
}
public async Task Thread2()
{
await Task.Delay(1000);
_sharedTask = Print2();
var result2 = await _sharedTask;
Console.WriteLine($"Result from Thread2: {result2}");
}
public async Task<int> Print1()
{
await Task.Delay(5000);
return 1;
}
public Task<int> Print2()
{
return Task.FromResult(2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment