async与await初步应用






using
System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form2 : Form { class Servo { bool bIsInPosi = false; public void StartMove() { this.bIsInPosi = false; } public bool IsInPosi() { return this.bIsInPosi; } public void Debug_InPosi() { this.bIsInPosi = true; } } Servo testServo = new Servo(); public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { } async private void btnStartMove_Click(object sender, EventArgs e) { Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " " + "运动开始"); testServo.StartMove(); bool bResult = await IsFinish(); Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " " + "运动结束了,结果=" + bResult.ToString()); } async Task<bool> IsFinish() { int timeOutSeconds = 10; DateTime dtStart = DateTime.Now; bool loop = true; while (loop) { await Task.Delay(100); if (testServo.IsInPosi()) { return true; } TimeSpan ts = DateTime.Now - dtStart; if (ts.TotalSeconds >= timeOutSeconds) { Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + " " + "运动超时了"); return false; } } return false; } private void btnInPosi_Click(object sender, EventArgs e) { testServo.Debug_InPosi(); } } }
原文地址:https://www.cnblogs.com/LongHuaiYu/p/10064093.html