基本信息
源码名称:c# 多线程更新WPF界面
源码大小:0.05M
文件格式:.rar
开发语言:C#
更新时间:2019-05-13
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading.Tasks;
using System.Threading;
namespace UpdateUIDemo
{
/*Dispatcher方法
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(Work);
}
private void Work()
{
Task task = new Task((tb) => Begin(this.first), this.first);
Task task2 = new Task((tb) => Begin(this.second), this.first);
Task task3 = new Task((tb) => Begin(this.Three), this.first);
task.Start();
task.Wait();
task2.Start();
task2.Wait();
task3.Start();
}
private void UpdateTb(TextBlock tb, string text)
{
tb.Text = text;
}
private void Begin(TextBlock tb)
{
int i = 100000000;
while (i > 0)
{
i--;
}
Random random = new Random();
String Num = random.Next(0, 100).ToString();
Action<TextBlock, String> updateAction = new Action<TextBlock, string>(UpdateTb);
tb.Dispatcher.BeginInvoke(updateAction, tb, Num);
}
}*/
/*任务调度器方法*/
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private readonly TaskScheduler _syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
private void Button_Click(object sender, RoutedEventArgs e)
{
Task.Factory.StartNew(SchedulerWork);
}
private void SchedulerWork()
{
Task.Factory.StartNew(Begin, this.first).Wait();
Task.Factory.StartNew(Begin, this.second).Wait();
Task.Factory.StartNew(Begin, this.Three).Wait();
}
private void Begin(object obj)
{
TextBlock tb = obj as TextBlock;
int i = 100000000;
while (i>0)
{
i--;
}
Random random = new Random();
String Num = random.Next(0,100).ToString();
Task.Factory.StartNew(() => UpdateTb(tb, Num),
new CancellationTokenSource().Token, TaskCreationOptions.None, _syncContextTaskScheduler).Wait();
}
private void UpdateTb(TextBlock tb, string text)
{
tb.Text = text;
}
}
}