Asynchronous DART异步/等待不等待 所以我一直在尝试用DART(我的核心语言是C++,以及嵌入式C派生)。因此,我的代码可能并不漂亮,因为我更多的是一个过程式程序员,但我正在努力学习。。。我一直在为等待同步的未来而挣扎,基本上,我无法让DART等待。下面的代码建立到小型嵌入式设备的套接字连接并提取信息。所有这些都可以工作,但请注意操作顺序应该是main(),从控制台获取一些信息,然后调用方法cardStatus以运行,并通过套接字连接从嵌入式设备获取信息。这就是等待的地方。当返回Future时,它应该转到printstuff()方法。我已经添加了按顺序排列的打印语句,内容如下: 这应该先打印出来 这应该是第二张 这应该是第三张
相反,由于cardstatus调用没有发生等待(这很耗时),我得到:Asynchronous DART异步/等待不等待 所以我一直在尝试用DART(我的核心语言是C++,以及嵌入式C派生)。因此,我的代码可能并不漂亮,因为我更多的是一个过程式程序员,但我正在努力学习。。。我一直在为等待同步的未来而挣扎,基本上,我无法让DART等待。下面的代码建立到小型嵌入式设备的套接字连接并提取信息。所有这些都可以工作,但请注意操作顺序应该是main(),从控制台获取一些信息,然后调用方法cardStatus以运行,并通过套接字连接从嵌入式设备获取信息。这就是等待的地方。当返回Future时,它应该转到printstuff()方法。我已经添加了按顺序排列的打印语句,内容如下: 这应该先打印出来 这应该是第二张 这应该是第三张,asynchronous,async-await,dart,Asynchronous,Async Await,Dart,相反,由于cardstatus调用没有发生等待(这很耗时),我得到: 这应该先打印出来 这应该是第三张 这应该是第二张 我在异步的使用上遵循了另一个线程,并且似乎至少遵循了一个可靠的使用方法(我尝试了一个.然后使用了一个具有类似结果的补足符,所以我觉得我缺少一些核心内容)。。但我已经坚持了一个星期了 下面的代码以及控制台输出 import 'dart:io'; import 'dart:async' show Future; const String STATUS = "#111111;"
- 这应该先打印出来
- 这应该是第三张
- 这应该是第二张
import 'dart:io';
import 'dart:async' show Future;
const String STATUS = "#111111;";
String defaultIP = "10.1.14.202";
int defaultConfigPort = 5111;
int defaultControlPort = 6722;
var card = new Map();
getInput(String defaults) {
String takenin = stdin.readLineSync();
if (takenin == '') takenin = defaults;
return takenin;
}
Future main() async {
stdout.write('What is the IP address of the card ($defaultIP): ');
String ipaddress = getInput(defaultIP);
defaultIP = ipaddress;
print ("This should print 1st");
stdout.writeln("Connecting to $defaultIP");
await cardStatus(defaultIP, defaultConfigPort, STATUS, card);
printstuff();
}
printstuff() {
stdout.writeln(card['subnet']);
print ("This should print 3rd");
}
Future cardStatus(String ip, int port, String message, Map card) {
return new Future.delayed(Duration.ZERO, () {
Socket.connect(ip, port).then((socket) {
print('Connected to: '
'${socket.remoteAddress.address}:${socket.remotePort}');
socket.listen((data) {
print(new String.fromCharCodes(data).trim());
List str1 = (new String.fromCharCodes(data).trim().split(','));
print(str1);
print ("This should print 2nd");
//var card = new Map();
card['ip'] = str1[0];
card['subnet'] = str1[1];
card['gateway'] = str1[2];
card['unknown'] = str1[3];
card['persist'] = str1[4] == 'true';
card['build'] = str1[5];
card['serial'] = str1[6].substring(0, 14);
card['cloudpassword'] = str1[6].substring(14, 20);
card['DNS'] = str1[7];
card['cloudhost'] = str1[8];
card['cloudenabled'] = str1[9] == 'true';
print(card['ip']);
},
onDone: () {
print("Done");
socket.destroy();
});
//Send the request
socket.write(message);
});
});
}
这是当前的控制台输出。请注意,如果cardStatus已完成,则null不应为null,它将被打印为str1
What is the IP address of the card (10.1.14.202):
This should print 1st
Connecting to 10.1.14.202
null
This should print 3rd
Connected to: 10.1.14.202:5111
>10.1.14.202,255.255.255.0,10.1.14.1,,0,435,F44900A60040F8000000,192.168.1.1,connect.tutuuu.com,0;
[>10.1.14.202, 255.255.255.0, 10.1.14.1, , 0, 435, F44900A60040F8000000, 192.168.1.1, connect.tutuuu.com, 0;]
This should print 2nd
10.1.14.202
Done
Process finished with exit code 0
谢谢你的帮助 套接字之前缺少
返回。连接。就目前的情况而言,您的代码只是开始连接,但在未来不会等待它。我强烈建议尽可能多地使用新的wait/async语法
下面是一个运行中的示例,它确实获得了google主页:
import 'dart:io';
import 'dart:async' show Future;
Future main() async {
print("This should print 1st");
await cardStatus('www.google.com', 80, 'GET /\nHTTP 1.1\n\n');
printstuff();
}
printstuff() {
print("This should print 3rd");
}
Future cardStatus(String ip, int port, String message) {
return new Future.delayed(Duration.ZERO, () {
return Socket.connect(ip, port).then((socket) {
print('Connected to: '
'${socket.remoteAddress.address}:${socket.remotePort}');
socket.listen((data) {
List str1 = (new String.fromCharCodes(data).trim().split(','));
print(str1.first);
print("This should print 2nd");
}, onDone: () {
print("Done");
socket.destroy();
}, onError: (e) {
print("Error while listening: $e");
});
socket.write(message);
});
});
}
下面是使用waits和try/catch来处理错误的稍微修改过的版本:
import 'dart:io';
import 'dart:async' show Future;
Future main() async {
print("This should print 1st");
await cardStatus('www.google.com', 80, 'GET /\nHTTP 1.1\n\n');
print("This should print 3rd");
}
Future<String> cardStatus(String ip, int port, String message) async {
var socket = await Socket.connect(ip, port);
print('Connected to: '
'${socket.remoteAddress.address}:${socket.remotePort}');
socket.write(message);
print("Sent request");
try {
var response = await socket.fold(
'',
(String acc, List<int> data) =>
acc + new String.fromCharCodes(data).trim());
print("Received response: ${response.substring(0, 10)}");
return response;
} finally {
socket.close();
}
}
导入'dart:io';
导入“dart:async”显示未来;
Future main()异步{
打印(“应先打印”);
等待cardStatus('www.google.com',80,'GET/\nHTTP 1.1\n\n');
打印(“这应该是第三次打印”);
}
未来cardStatus(字符串ip、int端口、字符串消息)异步{
var套接字=等待套接字。连接(ip,端口);
打印('连接到:'
“${socket.remoteAddress.address}:${socket.remotePort}”);
socket.write(消息);
打印(“发送请求”);
试一试{
var response=await socket.fold(
'',
(字符串acc,列表数据)=>
acc+新字符串.fromCharCodes(data.trim());
打印(“收到的响应:${response.substring(0,10)}”);
返回响应;
}最后{
socket.close();
}
}
我知道答案是肯定的,但这个问题很好,我一直在苦苦思索这个概念,所以这里有另一个让我理解的因素。在dartpad()中,尝试以下操作(注释在代码中):
导入'dart:async';
//只是创建一个持续时间供以后使用
持续时间=新的持续时间(毫秒:500);
void main(){
//这就是我被欺骗的地方,printStuff是异步的,所以默认情况下在并行处理中运行
//无需以某种方式调用函数(如go xxx用于goroutine)
//函数中有一个wait,因此它将仅在函数中等待
//i、 e.印刷品('a')开始,然后印刷品('b')立即开始……已在并行处理中
//运行它并检查输出
印刷品(‘a’);
印刷品(‘b’);
//基本上等待在函数中,所以printStuff仍然返回未来
//i、 e.printStuff('a')启动,但不等待完成以启动printStuff('b')
}
Future printStuff(字符串id)异步{
对于(int i=0;我以后会发布一个更简单的示例,其中大部分对您的问题不感兴趣。这不是问题。对此表示抱歉。非常感谢。这确实有效。我花了一点时间研究了这一点,以及等待语法。我想我是因为另一个线程说异步仅在“caller”方法中需要.我知道有许多线程与何时应该使用等待和何时不使用等待有关。使用的原则非常简单,但不知何故,我在何时使用它和何时不必使用它的实用性上被绊倒了…我将返回并重新阅读它…当我完整地阅读您的try/catch版本时,我会这样说ely是有道理的。再次感谢。这只是我被绊倒的一个例子——我最初的例子中的getInput()使用了stdin.readLineSync(),这本身就意味着等待和停止操作……很难解释,但我看到线程中的其他人也在为同样的概念而挣扎,我相信这与我在过程性单线程编程方面的基础教育有关。这非常棘手,我不知道有谁没有遇到过类似的问题:)
import 'dart:async';
//Just creating a duration to use later
Duration duration = new Duration(milliseconds: 500);
void main() {
//This is what tricked me, printStuff is async so running in parallel processing by default
//There is no need to call the function in a certain way (like a go xxx for a goroutine)
//there is an await in the function so it will wait inside the function only
//i.e. printStuff('a') starts then printStuff('b') starts straight away...already in prallel processing
//Run it and check the output
printStuff('a');
printStuff('b');
//Basically the await is in the function so printStuff is still returning a Future
//i.e. printStuff('a') starts but doesn't wait to complete to start printStuff('b')
}
Future<void> printStuff(String id) async {
for(int i = 0; i <= 5; ++i) {
//this await is waiting for the command to complete to move to the next iteration...
//the i iterations are done one after the other
await new Future.delayed(duration, () {
print(id + i.toString());
});
}
}
import 'dart:async';
Duration duration = new Duration(milliseconds: 500);
//becuase I use await in main now, I must make it return a future and be async
Future main() async {
//to make it happen one after the other, you need await at a call function level
await printStuff('a');
await printStuff('b');
//Basically this says complete printStuff('a'), then start printStuff('b')...
//and yes technically one doesn't need the second await becuase there is nothing after
}
Future<void> printStuff(String id) async {
for(int i = 0; i <= 5; ++i) {
await new Future.delayed(duration, () {
print(id + i.toString());
});
}
}