Currently, i am having difficulties to understand multi-tasking using async and await pattern. In order to get some basics, i have written the following test case;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int global_int = 10;
public async Task<int> RunAsyncTask()
{
// This method runs asynchronously.
await Task.Run(() => Calculate());
return global_int;
}
private int Calculate()
{
Console.WriteLine("Ticket count: " + --global_int);
return global_int;
}
private async void Start_Button_Click(object sender, RoutedEventArgs e)
{
List<Task<int>> list = new List<Task<int>>();
Console.WriteLine("\nReseting: " );
global_int = 10;
for (int i = 0; i < 10; i++)
{
var task = RunAsyncTask();
list.Add(task);
}
await Task.WhenAll(list.ToArray<Task<int>>());
Console.WriteLine("\nFinished: " + global_int);
}
}
Idea/Target:
10 customers, 10 tickets, every customer buys a ticket and at the end there will be no availiable ticket.
Problem:
When I run the code, i am actually getting not always the same result (Expecting 0 ticket always). Where is the actuall problem?
So, how can I write the code in a way that, result would be always same.
Output1:
Reseting:
Ticket count: 9
Ticket count: 8
Ticket count: 8
Ticket count: 7
Ticket count: 5
Ticket count: 6
Ticket count: 4
Ticket count: 3
Ticket count: 2
Ticket count: 1
Finished: 1
Output2:
Reseting:
Ticket count: 9
Ticket count: 8
Ticket count: 7
Ticket count: 6
Ticket count: 5
Ticket count: 4
Ticket count: 3
Ticket count: 2
Ticket count: 1
Ticket count: 0
Finished: 0