Scenario:
From MSDN:
For I/O-bound code, you await an operation that returns a Task or Task<T> inside of an async method.
For CPU-bound code, you await an operation that is started on a background thread with the Task.Run method.
You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 | using System;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class ProgramTaskRun
{
static async Task Main(string[] args)
{
while (true)
{
ProcessData();
string data = Console.ReadLine();
Console.WriteLine($"You entered: {data}");
}
}
private static async void ProcessData()
{
int result = await Task.Run(() => GenerateData());
Console.WriteLine("Process: " + result);
}
private static int GenerateData()
{
int size = 0;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 1000000; j++)
{
string value = j.ToString();
size += value.Length;
}
}
return size;
}
}
} |
|
No comments:
Post a Comment