I want to do some work with a coded in Delay with the UI active.
I thought I had TaskOfTResult_MethodSync
fixed with Task.Delay(delay).Wait();
. The problem is that blocks Task<int> taskS = TaskOfTResult_MethodSync(10000);
it does not immediately move on to the await
and the UI is not responsive. UI does not even paint until after the delay.
public async void TestTask3(int delay, CancellationToken ct)
works but it does not let me return a value.
If I use
int rslt = TestTask3(1000, token).Result;
public async Task<int> TestTask3(int delay, CancellationToken ct)
It hangs on int rslt = TestTask3(1000, token).Result;
This is not valid syntax await TestTask3(1000, token);
I don't mind using public async void TestTask3(int delay, CancellationToken ct)
but I would rather have work done with programmed Delay or Sleep that returns a value (rather than update a public property from the async method). What I want is to kick off a method / task then do some other work from the main tread. Then await
. After the await
some buttons get activated.
The reason I need a programmed in delay is it reads some instrument data and it needs to wait between reads to get a sample set.
Is there a way to get what I want?
I currently get what I need with BackGroundWorker but that but I was hoping to get there with task.
public MainWindow()
{
this.DataContext = this;
InitializeComponent();
Debug.WriteLine("before Task<int> taskS = TaskOfTResult_MethodSync(10000);");
Task<int> taskS = TaskOfTResult_MethodSync(10000);
Debug.WriteLine("before taskS.Wait");
taskS.Wait();
Debug.WriteLine("after taskS.Wait");
int i = taskS.Result;
Debug.WriteLine($"i = {i}");
Debug.WriteLine($"");
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
Debug.WriteLine("before TestTask3(1000, token);");
TestTask3(1000, token);
Debug.WriteLine("after TestTask3(1000, token);");
Thread.Sleep(2000);
Debug.WriteLine("after sleep on main TestTask3(1000, token);");
source.Cancel();
Debug.WriteLine("done Main");
}
public async void TestTask3(int delay, CancellationToken ct)
{
Debug.WriteLine($"TestTask3");
int ans = -1;
ans = await Task.Run(async () =>
{
// … do compute-bound work here
for (int j = 101; j <= 120; j++)
{
if(ct.IsCancellationRequested)
{
break;
}
await Task.Delay(delay);
ans = j;
Answer = j;
}
});
Debug.WriteLine($"TestTask3 {ans}");
Answer = ans;
//return ans;
}
Task<int> TaskOfTResult_MethodSync(int delay)
{
Debug.WriteLine($"TaskOfTResult_MethodSync delay = {delay} {DateTime.Now}");
int hours = 10;
Task.Delay(delay).Wait();
Debug.WriteLine($"TaskOfTResult_MethodSync after delay {DateTime.Now}");
return Task.FromResult(hours);
}