winform treeview控件异步定时刷新的一种实现方法

我只有一个winform窗体,上面只有两个控件,一个treeview,一个richtextbox用于显示状态信息。
在这里插入图片描述
treeview数据源大概如下所示。
在这里插入图片描述
直接上form1.cs的代码。

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsClient
{
    public partial class Form1 : Form
    {
        System.Threading.Timer timer;
        private delegate void BeginInvokeDelegate(string jsonResult);
        private delegate void BeginInvokeDelegateNoparam();
        private void StartTimer(System.Windows.Forms.TreeView treeview)
        {
            this.richTextBox1.Text = "开始获取数据";
            TimeSpan startTimeSpan = TimeSpan.Zero;
            //设置时间间隔30秒
            TimeSpan periodTimeSpan = TimeSpan.FromSeconds(30);
            //新建一个timer定时器
            timer = new System.Threading.Timer((e) => { GetOrgResource(this); }, null, startTimeSpan, periodTimeSpan);
        }
        private void GetOrgResource(System.Windows.Forms.Form treeview)

        {

            IAsyncResult aResult = null; /*= this.BeginInvoke(funDelegate, obj.ToString());*/

            string JsonResult = null;
            //await Task.Run(() => { return JsonResult = RequestWebservice.RequestClient(); })
            //        .ContinueWith(t =>
            //        {
            //            aResult = this.treeView1.BeginInvoke(new BeginInvokeDelegate(BeginInvokeMethod), t.Result);
            //            MessageBox.Show(t.Result);
            //        });

            //Func<string> func = () => { return JsonResult = RequestWebservice.RequestClient(); };
            //Task<string> task1 = new Task<string>(func);
            //JsonResult = await task1;
            //下面的RequestWebservice.RequestClient()方法是一个大数据量的耗时的执行方法,你可以自行设定这个方法,
            //public    static  string RequestClient()样式,返回的string 是一个json字符串。
            Action action = () => { JsonResult = RequestWebservice.RequestClient(); };
            //Task task = new Task(action);
            Task task1 = Task.Run(action);
            task1.Wait();
            DateTime time1 = System.DateTime.Now.AddMinutes(1);
            while (JsonResult == null||System.DateTime.Now==time1)
            {
                this.richTextBox1.Invoke(new BeginInvokeDelegateNoparam(() => { this.richTextBox1.Text += "-----本次获取数据为空,或者请求超时,将等待下次更新"
                    +System.DateTime.Now+"-----"; }));
                return;
            }
            aResult = this.treeView1.BeginInvoke(new BeginInvokeDelegate(BeginInvokeMethod), JsonResult);
                        //MessageBox.Show(JsonResult);
                    
            //aResult.AsyncWaitHandle.WaitOne(-1);
            //其实这里我们也可以设置一个过期时间,免得一直死循环
            while (aResult.IsCompleted == false || aResult == null)
            {
            }
            //Thread.Sleep(1000);
            this.richTextBox1.Invoke(new BeginInvokeDelegateNoparam(()=> { this.richTextBox1.Text += "-----获取完成"+DateTime.Now+"------"; }));
        }
        //生成一级节点 
        private void BeginInvokeMethod(string jsonResult)
        {
            treeView1.Nodes.Clear();
            DataTable dt1 = JsonConvert.DeserializeObject<DataTable>(jsonResult);
            DataRow[] rows = dt1.Select("Len(OrgCode)=4");
            if (rows.Count() == 0)
            {
                return;
            }
            foreach (var item in rows)
            {
                if (item["ParentCode"].ToString() == "0" && item["OrgCode"].ToString().Length == 4)
                {
                    TreeNode rootNode = new TreeNode();
                    rootNode.Tag = item;
                    rootNode.Text = item["Name"].ToString();
                    rootNode.Name = item["OrgCode"].ToString();
                    treeView1.Nodes.Add(rootNode);
                    //CreateChildNode(TreeNode rootNode , DataTable dt1);
                    CreateChildNode(rootNode, dt1);
                }
            }
        }
        //递归生成子节点
        protected void CreateChildNode(TreeNode parentNode, DataTable datatable)
        {
            DataRow[] rowlist = datatable.Select("ParentCode=" + parentNode.Name);
            if (rowlist.Count() == 0) { return; }
            foreach (var item in rowlist)
            {
                TreeNode rootNode = new TreeNode();
                rootNode.Tag = item;
                rootNode.Text = item["Name"].ToString();
                rootNode.Name = item["OrgCode"].ToString();
                parentNode.Nodes.Add(rootNode);
                CreateChildNode(rootNode, datatable);
            }
        }
        public Form1()
        {
            InitializeComponent();
            StartTimer(this.treeView1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37326058/article/details/85723532