c#关于异步编程?

c#5.0加入的语法糖async,await这种基于任务的异步编程方式简单了,我有个问题一直想不明白,既然异步是为了不阻塞线程,await关键字不就是…
关注者
230
被浏览
60,467

22 个回答

await 不是等待, await 还是回调,

转化过程:

g0: callback

void DoA( data , addressOf(DoB) )  {blah blah ;  ThreadPool.Queue(addressof (DoB));}
void DoB( data , addressOf(DoC) )  {blah blah ;  ThreadPool.Queue(addressof (DoC));}
void DoC( data )  {output blah;}

g0.5 event base:

void DoA(data) { blah blahA sync part; RaiseEvent(AFinished,this,eventArg)};
void DoB(data) { blah blahB sync part; RaiseEvent(BFinished,this,eventArg)};
void DoC(data) { blah blahC sync part; RaiseEvent(CFinished,this,eventArg)};
AFinished += (sender,args) =>{ DoB(args); } 
BFinished += (sender,args) =>{ DoC(args); }
CFinished += (sender,args) =>{ Output( args); }

包括 promise 和 task 都是上面两种的变形 属于 g1吧,。

g1: continue / then

Task DoAAsync(data) { blah blahA sync part;  return asyncExecuteTaskA;
Task DoBAsync(data) { blah blahB sync part; return asyncExecuteTaskB;};
Task DoC(data) { blah blahC sync part; };

那么就可以写出

DoAAsync(data)
    .ContinueWith(t=>DoBAsync(t.Result))
    .ContinueWith(t=>DoCAsync(t.Result))

上面三个看起来都一样, 基本上是三段逻辑,但是放在三个函数 后来有人觉得不好管理,于是有人写了一个函数 做成了一个状态机

g2:State Machine

void DoABC( state)
     switch  (state)
        case 0:
             blah blah A sync part:
             Thread.Queue(addressof(DoABC) , 1 );
        case 1:
             blah blah B sync part;
             Thread.Queue(addressof(DoABC) , 2 );
        case 2
             blash C sync Part
           output();

加上语法糖就变成了

g2.5:

async Task DoABCAsync()
    Blah A sync part;
     await  blahAsync();
     Blah B sync part;