我使用了raspberry pi 3和Windows IoT构建了一个RFID阅读器。 当我复制这个lib RFID RC522 Raspberry PI 2 Windows IOT并为这个lib创建新类时。我有一些问题。
在原始命名空间中,我添加了一个新类'startmfrc522'。
public class startmfrc522 {
Mfrc522 mfrc = new Mfrc522();
public async Task<bool> start() {
System.Diagnostics.Debug.WriteLine("start RFID");
await mfrc.InitIO();
System.Diagnostics.Debug.WriteLine("finish Init");
return true;
}
public async Task<string> readtag() {
for (int i = 0; i < 5; i++) {
System.Diagnostics.Debug.WriteLine("start read tag");
if (mfrc.IsTagPresent()) {
System.Diagnostics.Debug.WriteLine("success");
string uid = mfrc.ReadUid().ToString();
mfrc.HaltTag();
return uid;
}
else {
mfrc.HaltTag();
return "fail";
}
await Task.Delay(1000);
System.Diagnostics.Debug.WriteLine("Delay for 1 s");
}
return "fail";
}
}
在主页中,我使用此代码启动rfid阅读器并阅读标签
startmfrc522 rfid = new startmfrc522();
while (!rfid.start().Result){
System.Diagnostics.Debug.Write(".");
}
System.Diagnostics.Debug.WriteLine(rfid.readtag());
第一个问题是VS 2015告诉我使用'bool x = await start()',我将其更改为'bool result = await start()',仍然无效。
第二个问题是我测试读取标签,看起来像mfrc.InitIO没有完成并立即读取标签。 但是我添加'async'和'await',它不应该等待InitIO完成工作并读取标签吗?
第三个问题是'Task.Sleep'无法正常工作,我认为它应该等待五次,总等待5s。
我想我不太了解'await'和'async'。 希望有人可以告诉我它是什么以及如何更改我的代码!
答案 0 :(得分:1)
public async Task<string> readtag()
await Task.Delay(1000);
System.Diagnostics.Debug.WriteLine(await readtag());
await rfid.start()
和await rfid.readtag()
,也应该是基于任务的(async Task mainpage()
)