gpt4 book ai didi

c# - WPF 布朗运动 : updating state with a thread

转载 作者:太空宇宙 更新时间:2023-11-03 16:23:51 24 4
gpt4 key购买 nike

这是 WPF 中的一个小布朗运动演示:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;

namespace WpfBrownianMotion
{
static class MiscUtils
{
public static double Clamp(this double n, int low, double high)
{
return Math.Min(Math.Max(n, low), high);
}
}

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

Width = 500;
Height = 500;

var canvas = new Canvas();

Content = canvas;

var transform = new TranslateTransform(250, 250);

var circle = new Ellipse()
{
Width = 25,
Height = 25,
Fill = Brushes.PowderBlue,
RenderTransform = transform
};

canvas.Children.Add(circle);

var random = new Random();

var thread =
new Thread(
() =>
{
while (true)
{
Dispatcher.Invoke(
DispatcherPriority.Normal,
(ThreadStart)delegate()
{
transform.X += -1 + random.Next(3);
transform.Y += -1 + random.Next(3);

transform.X = transform.X.Clamp(0, 499);
transform.Y = transform.Y.Clamp(0, 499);
});
}
});

thread.Start();

Closed += (s, e) => thread.Abort();
}
}
}

我的问题是这样的。在没有使用标准 WPF 动画工具的情况下,上述使用 ThreadDispatcher 的方法是否是推荐的方法?

一般来说,我有时会遇到需要更新和渲染的状态,而动画工具并不适合。所以我需要一种方法来在单独的线程中进行更新和渲染。只是想知道上述方法是否正确。

最佳答案

Clemens 在上面的评论中建议使用 DispatcherTimer。实际上,这确实大大简化了代码。这是采用这种方法的版本:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfBrownianMotion
{
static class MiscUtils
{
public static double Clamp(this double n, int low, double high)
{
return Math.Min(Math.Max(n, low), high);
}
}

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

Width = 500;
Height = 500;

var canvas = new Canvas();

Content = canvas;

var transform = new TranslateTransform(250, 250);

var circle = new Ellipse()
{
Width = 25,
Height = 25,
Fill = Brushes.PowderBlue,
RenderTransform = transform
};

canvas.Children.Add(circle);

var random = new Random();

var timer = new DispatcherTimer();

timer.Tick += (s, e) =>
{
transform.X += -1 + random.Next(3);
transform.Y += -1 + random.Next(3);

transform.X = transform.X.Clamp(0, 499);
transform.Y = transform.Y.Clamp(0, 499);
};

timer.Start();
}
}
}

关于c# - WPF 布朗运动 : updating state with a thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13153470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com