云起工作室 15711107967
12_异步/线程
2024-06-13 14:54:25

事件队列【异步处理】

Future() 相当于 new Promise()

Future.await() 相当于 new Promise.all()

getData() async{

await Future((){

执行逻辑

})

print("dd");

}


Future((){

return "";

}).then((value){


}),catchError((e){})


多链式异步

Future.await([

Future((){return ""}),

Future((){return ""}),

Future((){return ""}),

]).then((val){

}).catchError((err){})


微任务 队列

比Future先执行

scheduleMicrotask((){

})


sleep

sleep(Duration(seconds:10))


多线程Isolate.spawn

void test(){

print("1");

Isolate.spawn(func,10);

sleep(Duration(seconds:2));

print("2");

}

func(int count){

print("3");

}

执行顺序为 1,3,2



线程里的方法不会影响到外部变量,如:

var a= "10";

void test(){

print("1");

Isolate.spawn(func,10);

sleep(Duration(seconds:2));

print(a); //输出 10 而不是100

}

func(int count){

a="100";

print("3");

}

如何让线程里的方法影响到外部变量

var a= "10";

void test() async {

print("1");

ReceivePort port = ReceivePort();

Isolate iso =await Isolate.spawn(func,port.sendPort);

port.listen((message){

a=message;

port.close();

iso.kill();

})

sleep(Duration(seconds:2));

print(a);

}

func(SendPort port){

a="100";

send.send("100");

}


compute 是 Isolate.spawn的简化版,不需要再kill

并且可以直接使用返回值,不需要再借用ReceivePort


定时循环

int count = 0;

Timer.periodic(Duration(seconds:2),(timer){

count ++;

print(count);

if(count==99){

timer.cancel(); //终止定时循环

}

})


在页面销毁timer

场景:在页面设置保持状态的情况下,如果来回切换页面,会创造多个timer 造成内存泄漏

class _ChatPage extends State<ChatPage>{

Timer _timer;

void dispose(){

if(_timer!=null && _timer.isActive){

_timer.cancel();

}

super.dispose();

}

void initState(){

_timer = Timer.periodic(Duration(seconds:2),(timer){

//处理逻辑

timer.cancel()

})

}

}