110,534
社区成员
发帖
与我相关
我的任务
分享
<Window x:Class="WpfApplication.Moniter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Moniter" Height="278" Width="586">
<Grid Height="174" Width="478">
<Button Content="Button1" Height="33" HorizontalAlignment="Left" Margin="26,25,0,0" Name="button1" VerticalAlignment="Top" Width="86" />
<Button Content="Button2" Height="33" HorizontalAlignment="Left" Margin="137,25,0,0" Name="button2" VerticalAlignment="Top" Width="86" />
<Button Content="Button3" Height="33" HorizontalAlignment="Left" Margin="243,25,0,0" Name="button3" VerticalAlignment="Top" Width="86" />
<Button Content="Start" Height="23" HorizontalAlignment="Left" Margin="383,105,0,0" Name="button4" VerticalAlignment="Top" Width="75" Click="button4_Click" />
<Button Content="Stop" Height="23" HorizontalAlignment="Left" Margin="383,139,0,0" Name="button5" VerticalAlignment="Top" Width="75" Click="button5_Click" />
</Grid>
</Window>
namespace WpfApplication
{
/// <summary>
/// Moniter.xaml 的交互逻辑
/// </summary>
public partial class Moniter : Window
{
public delegate void RefreshHandler();
Machine machine = new Machine();
public Moniter()
{
InitializeComponent();
Task task = new Task(() =>
{
while (true)
{
Dispatcher.Invoke(new RefreshHandler(Refresh), null);
}
});
task.Start();
}
public void Refresh()
{
for (int a = 1; a <= 3; a++)
{
Button btn = FindName("button" + a) as Button;
if (machine.status == a)
{
btn.Background = Brushes.Green;
}
else
{
btn.Background = Brushes.Gray;
}
}
}
private void button4_Click(object sender, RoutedEventArgs e)
{
machine.Start();
}
private void button5_Click(object sender, RoutedEventArgs e)
{
machine.Stop();
}
}
public class Machine
{
public int status = 0;
private Task task;
private int offon = 0;
public void Start()
{
task = new Task(Job);
offon = 1;
task.Start();
}
public void Stop()
{
if (task != null)
{
offon = 0;
}
status = 0;
}
private void Job()
{
while (true && offon != 0)
{
System.Random r = new Random();
status = r.Next(1, 4);
System.Threading.Thread.Sleep(150);
}
}
}
}
static int temp = 0;
static void Main(string[] args)
{
Task task = new Task(new Action(A));
task.Start();
Task task2 = new Task(new Action(B));
task2.Start();
Console.ReadLine();
}
static void A()
{
while (true)
{
temp = new Random().Next(1, 10);
System.Threading.Thread.Sleep(500);
}
}
static void B()
{
while (true)
{
Console.WriteLine(temp);
System.Threading.Thread.Sleep(500);
}
}
简化一下你的代码,仔细调试一下,关键点就那么几个.