What is better. Maybe async, await is not so complicated.
Can I say it like this?
We do the functions synchronously, who needs it asynchronously must solve this himself.
The used source
https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html
Conclusion: do not use Task.Run in the implementation of the method; instead, use Task.Run to call the method.
The key here is that the solution does not belong in the service. It belongs in the UI layer itself.
Let the UI layer solve its own problems and leave the service out of it.
var result = await Task.Run(() => MyServerData.IsProductResult(77));
return result;
I have a very difficult time with the spelling.
How can I still write this? How do I pass parameters?
I have seen something like this.
var result = await Task.Run((t1,t2,t3) => XXX
t3 is the return value. t1,t2 the passing value?
How do I **cancel **the function, the function when I would click cancel.
Is there a pattern way?
Here my sample code.
public class ServerData
{
public int Index { set; get; }
public string Code { set; get; }
public string BestBefore { set; get; }
}
public class ServerDataList : List<ServerData>
{
public bool DataReady { set; get; }
public void GetServerData()
{
DataReady = false;
for (int i = 0; i < 300000; i++)
{
Add(new ServerData()
{
BestBefore = "12/2023",
Code = $"{i,22:D12}",
Index = i
});
Trace.WriteLine($"Code= '{this[Count - 1].Code}', ThreadID= '{Thread.CurrentThread.ManagedThreadId}'");
Thread.Sleep(2);
}
DataReady = true;
}
public bool IsDataFromServerReady()
{
while (!DataReady)
{
Thread.Sleep(50);
}
return DataReady;
}
public bool IsProductResult(int amount)
{
if (amount > 30)
return true;
return false;
}
}
public class MyService
{
ServerDataList MyServerData = new ServerDataList();
public int Process()
{
// Tons of work to do in here!
for (int i = 0; i != 10000000; ++i)
{
Trace.WriteLine($"Work {i}, ThreadID= '{Thread.CurrentThread.ManagedThreadId}'");
if (i == 10000)
EventIn();
if (i == 10100)
{
EventStart();
// break;
}
if (i == 10900)
{
var ret = EventOut();
// break;
}
}
return 42;
}
public async void EventIn()
{
await Task.Run(() => MyServerData.GetServerData());
MessageBox.Show("EventIn");
}
public async void EventStart()
{
//ServerDataList MyServerDataSub = new ServerDataList();
await Task.Run(() => MyServerData.IsDataFromServerReady());
MessageBox.Show("EventStart");
}
public async Task<bool> EventOut()
{
var result = await Task.Run(() => MyServerData.IsProductResult(77));
return result;
// return await Task.Run(() => MyServerData.IsProductResult(45)).Result;
}
}
MyService MyServiceObject = new MyService();
private async void btnTASK_Click(object sender, EventArgs e)
{
MyServiceObject = new MyService();
await Task.Run(() => MyServiceObject.Process());
MessageBox.Show("TEST Mandelbrot Ready");
}