kotlin的suspend对比csharp的async&await
协程的出现大大降低了异步编程的复杂度,可以让我们像写同步代码一样去写异步代码,如果没有它,那么很多异步的代码都是需要靠回调函数来一层层嵌套,这个在我之前的一篇有介绍 rxjava回调地狱-kotlin协程来帮忙
本篇文章主要介绍
-
kotlin的suspend函数在编译生成了怎样的代码 -
csharp的async&await在编译生成了怎么样的代码 -
这两者相比较,引发怎样的思考
kotlin的suspend函数demo

这里针对kotlin的语法以及协程的具体用法细节不过多介绍,就当你已了解
稍微注意下runBlocking函数比较特别,
如下图:它接受了一个suspend的block函数

所以我上面的demo这里面有其实有三个suspend函数!
在idea我们可以把这个kotlin代码反编译成java代码

这个反编译后的java代码 有很多报错是无法直接copy出来运行的(这就没有csharp做的好,csharp反编译出来的代码至少不会报红),

看代码的确是一个状态机控制函数和一个匿名类,还原成正常的java代码如下:

比如test1函数
public static Object test1(Continuation continuation) {
CoroutineTest1 continuationTest1;
label20:
{
if (continuation instanceof CoroutineTest1) {
continuationTest1 = (CoroutineTest1) continuation;
int i = continuationTest1.label & Integer.MIN_VALUE;
if (i != 0) {
continuationTest1.label -= Integer.MIN_VALUE;
}
break label20;
}
continuationTest1 = new CoroutineTest1(continuation);
}
Object result = (continuationTest1).result;
Object var4 = IntrinsicsKt.getCOROUTINE_SUSPENDED();
String var1;
switch ((continuationTest1).label) {
case 0:
ResultKt.throwOnFailure(result);
var1 = "test1-start";
System.out.println(var1);
(continuationTest1).label = 1;
if (test2(continuationTest1) == var4) {
return var4;
}
break;
case 1:
ResultKt.throwOnFailure(result);
break;
default:
throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
}
var1 = "test1-end";
System.out.println(var1);
return Unit.INSTANCE;
}
final static class CoroutineTest1 extends ContinuationImpl {
Object result;
int label;
public CoroutineTest1(@Nullable Continuation