Thanks for your comments. I have build a simple example which calls some methods with delays. The output is as expected in the right order (due to the different delays).
My Problem is now:
I have a webservice in a external static class (see below).
This wrapper has no async keyword and there is no async call in the webservice client (webreference to external service).
Would it help to put the Wrapper in a instanced class so that the every task calls is own instance of the wrapper?
public static class Wrapper {
public static string CallWebservice(string param) {
var client = new Webservice.Client();
return client.Method(param);
}
}
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace AsyncTest
{
public static class Helpers
{
public static MainWindow mainWindow = null;
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Helpers.mainWindow = this;
}
public static void AddLog(string text)
{
Helpers.mainWindow.Dispatcher.Invoke(
() => Helpers.mainWindow.LblOutput.Content += DateTime.Now.ToString() + $" [{text}]\r\n",
DispatcherPriority.Background
);
}
private async void ButtonDoAsync_Click(object sender, RoutedEventArgs e)
{
AddLog("Button Click:Start");
StartAsync();
for (var i = 0; i < 5; i++)
{
AddLog($"Button Click:Wait {i}");
await Task.Delay(500);
}
AddLog("Button Click:End");
}
static async void StartAsync()
{
var tasks = new Func<Task>[]
{
() => DoSomethingAsync("t1",800),
() => DoSomethingAsync("t2",350),
() => DoSomethingAsync("t3",450)
};
await Task.WhenAll(tasks.Select(task => task()).ToArray());
}
static async Task DoSomethingAsync(string taskId, int delay)
{
for (var i = 0; i < 5; i++)
{
AddLog(Wrapper.CallWebservice(taskID));
AddLog($"Async {taskId} {i}");
await Task.Delay(delay);
}
}
}
}