using System.Threading;
class Application
{
// 入口函数必须可以等待
public static async Task Main()
{
System.Console.WriteLine("Main Start");
var renderTask = RenderAsync();
Console.WriteLine("Start Rendering");
await renderTask;
Console.WriteLine("Render Done");
System.Console.WriteLine("Main Finish");
}
static async Task<List<float>> RenderAsync()
{
System.Action<float> drawProgress = (Value) =>
{
const int Length = 64;
string Line = "\r[";
for (int i = 0; i < Length; i += 1)
{
if (Length * Value > i) Line += "*";
else Line += " ";
}
Line += "]";
Console.Write(Line);
};
const int renderSize = 64;
List<float> renderResult = new List<float>();
List<Task<float>> renderTasks = new List<Task<float>>();
for (int i = 0; i < renderSize; i += 1)
{
renderTasks.Add(Task.Run(() =>
{
return CastRay((uint)i);
}));
}
// Wait a Single Task at one time
while (renderTasks.Count > 0)
{
Task<float> finishedTask = await Task.WhenAny(renderTasks);
// Save the Result Here
renderTasks.Remove(finishedTask);
drawProgress(1.0f - (1.0f * renderTasks.Count / renderSize));
}
// Wait All Tasks
/*
await Task.WhenAll(renderTasks);
renderResult.Capacity = renderSize;
for (int i = 0; i < renderSize; i += 1)
{
renderResult.Add(renderTasks[i].Result);
}
*/
drawProgress(1.0f);
Console.WriteLine("");
return renderResult;
}
// Real Compute
static float CastRay(uint pixelIndex)
{
Thread.Sleep(1000);
return (float)pixelIndex;
}
}