You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF状态栏实现计时启停、JSON序列化及TCP发送功能求助

WPF状态栏功能实现方案

需求说明

  • 状态栏需展示信息,包含启停流程按钮,显示已启动/处理中/已停止状态及已耗时
  • 点击Start按钮后每500ms重复执行指定操作
  • Start触发时序列化对象并通过TCP Socket发送JSON字符串
  • 点击Stop按钮终止循环流程

修改后的前端XAML代码

<Window x:Class="StatusBar.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Simple Status Bar" Height="350" Width="525">
    <Grid Background="BlanchedAlmond">
        <TextBlock FontSize="50" Margin="200,-12,175,258" RenderTransformOrigin="1.443,0.195">Timer</TextBlock>
        <!-- 已耗时显示 -->
        <TextBlock x:Name="clocktxtblock" FontSize="70" Margin="118,38,37,183">00:00:00</TextBlock>
        <!-- 状态显示 -->
        <TextBlock x:Name="statusTextBlock" FontSize="20" Margin="180,100,180,0" VerticalAlignment="Top" Foreground="Green"/>
        <Button x:Name="startbtn" Margin="38,137,350,126" Background="SkyBlue" Content="Start" FontSize="30" Click="startbtn_Click" />
        <Button x:Name="stopbtn" Margin="200,137,190,126" Background="SkyBlue" Content="Stop" FontSize="30" Click="stopbtn_Click" IsEnabled="False"/>
        <Button x:Name="resetbtn" Margin="360,137,28,126" Background="SkyBlue" Content="Reset" FontSize="30" Click="resetbtn_Click" />
        <ListBox x:Name="elapsedtimeitem" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="433" Margin="56,199,0,0"/>
    </Grid>
</Window>

修改后的WPF C#代码

using System;
using System.Diagnostics;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Windows;
using System.Windows.Threading;

namespace StatusBar
{
    public partial class MainWindow : Window
    {
        private readonly DispatcherTimer _taskTimer = new DispatcherTimer();
        private readonly Stopwatch _stopwatch = new Stopwatch();
        private TcpClient _tcpClient;
        private NetworkStream _networkStream;
        private string _currentTime = string.Empty;

        public MainWindow()
        {
            InitializeComponent();
            // 设置定时任务间隔为500ms
            _taskTimer.Interval = TimeSpan.FromMilliseconds(500);
            _taskTimer.Tick += TaskTimer_Tick;
        }

        private void TaskTimer_Tick(object sender, EventArgs e)
        {
            if (_stopwatch.IsRunning)
            {
                // 更新已耗时显示
                TimeSpan ts = _stopwatch.Elapsed;
                _currentTime = $"{ts.Minutes:00}:{ts.Seconds:00}:{ts.Milliseconds / 10:00}";
                clocktxtblock.Text = _currentTime;
                statusTextBlock.Text = "处理中...";

                // 执行重复操作(示例:序列化对象并发送)
                ExecuteRepeatedTask();
            }
        }

        private async void ExecuteRepeatedTask()
        {
            try
            {
                // 示例对象,可替换为业务对象
                var dataToSend = new
                {
                    Status = "Processing",
                    ElapsedTime = _currentTime,
                    Timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
                };

                // JSON序列化
                string jsonString = JsonSerializer.Serialize(dataToSend);
                byte[] buffer = Encoding.UTF8.GetBytes(jsonString);

                // 发送到TCP服务器(需替换为实际服务器地址和端口)
                if (_tcpClient?.Connected == true)
                {
                    await _networkStream.WriteAsync(buffer, 0, buffer.Length);
                }
            }
            catch (Exception ex)
            {
                statusTextBlock.Text = $"发送失败: {ex.Message}";
            }
        }

        private async void startbtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 初始化TCP连接
                _tcpClient = new TcpClient();
                await _tcpClient.ConnectAsync("127.0.0.1", 8888); // 替换为实际服务器地址和端口
                _networkStream = _tcpClient.GetStream();

                _stopwatch.Start();
                _taskTimer.Start();

                startbtn.IsEnabled = false;
                stopbtn.IsEnabled = true;
                statusTextBlock.Text = "已启动";
            }
            catch (Exception ex)
            {
                statusTextBlock.Text = $"启动失败: {ex.Message}";
            }
        }

        private void stopbtn_Click(object sender, RoutedEventArgs e)
        {
            _taskTimer.Stop();
            if (_stopwatch.IsRunning)
            {
                _stopwatch.Stop();
            }

            // 关闭TCP连接
            _networkStream?.Close();
            _tcpClient?.Close();

            elapsedtimeitem.Items.Add(_currentTime);
            startbtn.IsEnabled = true;
            stopbtn.IsEnabled = false;
            statusTextBlock.Text = "已停止";
        }

        private void resetbtn_Click(object sender, RoutedEventArgs e)
        {
            _stopwatch.Reset();
            clocktxtblock.Text = "00:00:00";
            statusTextBlock.Text = string.Empty;
            elapsedtimeitem.Items.Clear();
        }

        protected override void OnClosed(EventArgs e)
        {
            // 窗口关闭时清理资源
            _taskTimer.Stop();
            _networkStream?.Dispose();
            _tcpClient?.Dispose();
            base.OnClosed(e);
        }
    }
}

关键实现说明

  • 修正原代码中**错误使用StatusBar类代替Stopwatch**的问题,Stopwatch是.NET专门用于高精度计时的类
  • 使用DispatcherTimer实现500ms定时任务,确保操作在UI线程执行,避免跨线程UI访问错误
  • 采用System.Text.Json进行JSON序列化,若需使用Newtonsoft.Json,需安装对应NuGet包并替换序列化逻辑
  • TCP通信使用异步方法,避免阻塞UI线程导致界面卡顿
  • 实时更新状态文本,清晰展示流程的已启动/处理中/已停止状态
  • 窗口关闭时自动清理TCP连接和定时器资源,避免内存泄漏

内容的提问来源于stack exchange,提问作者Juju22 Nimza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:50:34