运行界面:
代码部分:
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;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public static string resultWeight { get; set; } = "";
Stopwatch stopwatch = new Stopwatch();
public Form1()
{
InitializeComponent();
Task.Run(RunThread);
}
private async Task RunThread()
{
while (true)
{
stopwatch.Restart();
var t = await AsyncWeight();
Console.WriteLine($"状态:{t} 时间:{stopwatch.ElapsedMilliseconds}");
// Task.Delay(10).Wait();
Thread.Sleep(10);
Console.WriteLine($"状态:{t} 时间:{stopwatch.ElapsedMilliseconds}");
}
}
/// <summary>
/// Async修饰的方法 调用方法 var t= await AsyncWeight();
/// </summary>
/// <returns></returns>
public static async Task<bool> AsyncWeight()
{
var result = await WasteWeight();
return result;
}
/// <summary>
/// 等待
/// </summary>
/// <returns></returns>
private static async Task<bool> WasteWeight()
{
return await Task.Run(() =>
{
int i = 0;
bool b = true;
bool Return = false;
while (b)
{
if (resultWeight.Length > 2) //得到重量
{
b = false;
Return = true;
}
else if (i >= 400) //等待40秒
{
b = false;
Return = false;
}
i++;
Console.WriteLine($"i={i}");
// Task.Delay(1000).Wait();
Thread.Sleep(1000);
}
return Return;
});
}
private void button1_Click(object sender, EventArgs e)
{
resultWeight = string.Empty;
}
private void button2_Click(object sender, EventArgs e)
{
resultWeight = "1234566778";
}
}
}