c#でTaskを返す<br>Tとの大まかな使い方
2852 ワード
, , , , , 。
, :PreCheck(),Check(),AfterCheck()。 , , Task。 : , , return 。
, : protected virtual Task PreCheck() , return Task.Factory.StartNew(()=> { return true; }); ; protected virtual async Task Check() , return true; ; 。
:
1、Main :
static async System.Threading.Tasks.Task Main(string[] args)
{
var test = new ExtendClass();
await test.Main();
Console.WriteLine("Main Program here");
Console.ReadKey();
}
2、MyBaseClass
public class MyBaseClass
{
public async Task Main()
{
if (!await PreCheck())
{
Console.WriteLine("PreCheck not pass");
return;
}
else
{
Console.WriteLine("PreCheck pass");
}
if (!await Check())
{
Console.WriteLine("Check not pass");
return;
}
else
{
Console.WriteLine("Check pass");
}
if (!await AfterCheck())
{
Console.WriteLine("AfterCheck not pass");
return;
}
else
{
Console.WriteLine("AfterCheck pass");
}
Console.WriteLine("Well done");
}
protected virtual Task PreCheck()
{
Console.WriteLine("Base PreCheck");
return Task.Factory.StartNew(()=> { return true; });
}
protected virtual async Task Check()
{
Console.WriteLine("Base Check");
return true;
}
protected virtual Task AfterCheck()
{
Console.WriteLine("Base AfterCheck");
return Task.Factory.StartNew(() => { return true; });
}
}
3、ExtendClass
class ExtendClass:MyBaseClass
{
private bool someCondiction = true;
protected override async Task PreCheck()
{
if (!await base.PreCheck())
return false;
return await AnotherPreCheck();
}
protected override async Task Check()
{
if(someCondiction)
{
Console.WriteLine("Extend Check");
return true;
}
else
{
return await base.Check();
}
}
protected override Task AfterCheck()
{
return base.AfterCheck();
}
private async Task AnotherPreCheck()
{
Console.WriteLine("Extend AnotherPrecheck");
return true;
}
}