<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Grid.Column="0" Command="{Binding ClickCmd}" Content="Click Cmd"/>
<Button Grid.Row="0" Grid.Column="1" Command="{Binding CancelCmd}" Content="Cancel Cmd"/>
<ListBox Grid.Row="1" BorderBrush="Black" BorderThickness="3" Grid.RowSpan="2" ItemsSource="{Binding ContentOb,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input; namespace WpfApplication1.Model
{
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute; public event EventHandler CanExecuteChanged; public DelegateCommand(Action<object> execute)
: this(execute, null)
{
} public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
} public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
} return _canExecute(parameter);
} public void Execute(object parameter)
{
_execute(parameter);
} public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using WpfApplication1.Model;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows;
using System.IO;
using Newtonsoft.Json; namespace WpfApplication1.ViewModel
{
public class WpfVM : INotifyPropertyChanged
{
private WpfVM()
{ }
public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propName)
{
var handler = PropertyChanged;
if(handler!=null)
{
handler?.Invoke(this, new PropertyChangedEventArgs(propName));
}
} private static WpfVM Wpfvm;
private static readonly object objLock = new object();
public static WpfVM GetWpfVM()
{
lock(objLock)
{
if(Wpfvm == null)
{
Wpfvm = new WpfVM();
}
return Wpfvm;
}
} private static CancellationTokenSource cts=new CancellationTokenSource(); #region Commands
private DelegateCommand ClickCmdValue;
public DelegateCommand ClickCmd
{
get
{
if(ClickCmdValue==null)
{
ClickCmdValue = new DelegateCommand(ClickCmdExecuted);
}
return ClickCmdValue;
}
} private string ContentValue;
public string Content
{
get
{
return ContentValue;
}
set
{
if(value!=ContentValue)
{
ContentValue = value;
OnPropertyChanged("Content");
}
}
} private bool IsCancelledValue=false;
public bool IsCancelled
{
get
{
return IsCancelledValue;
}
set
{
if(value!=IsCancelledValue)
{
IsCancelledValue = value;
OnPropertyChanged("IsCancelled");
}
}
}
private void ClickCmdExecuted(object obj)
{
ContentOb = new ObservableCollection<string>();
Task.Run(() =>
{
while (!cts.IsCancellationRequested)
{
Content = DateTime.Now.ToString("yyyyMMddHHmmssffff");
App.Current.Dispatcher.BeginInvoke((Action)delegate
{
ContentOb.Add(Content);
});
System.Diagnostics.Debug.WriteLine(Content);
}
},cts.Token);
} private DelegateCommand CancelCmdValue;
public DelegateCommand CancelCmd
{
get
{
if(CancelCmdValue==null)
{
CancelCmdValue = new DelegateCommand(CancelCmdValueExecuted);
}
return CancelCmdValue;
}
} private void CancelCmdValueExecuted(object obj)
{
cts.Cancel();
IsCancelled = true;
System.Diagnostics.Debug.WriteLine("Cancelled!");
string msJsonSerializerString = JsonConvert.SerializeObject(ContentOb,Formatting.Indented);
string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".txt";
using(StreamWriter streamWriter=new StreamWriter(fileName,true,Encoding.UTF8))
{
streamWriter.WriteLine(msJsonSerializerString);
}
}
#endregion #region Properties
private ObservableCollection<string> ContentObValue;
public ObservableCollection<string> ContentOb
{
get
{
return ContentObValue;
}
set
{
if(value!=ContentObValue)
{
ContentObValue = value;
OnPropertyChanged("ContentOb");
}
}
}
#endregion
}
}
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApplication1.ViewModel; namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
WpfVM vm = WpfVM.GetWpfVM();
this.DataContext = vm;
}
}
}

private void ClickCmdExecuted(object obj)
{
ContentOb = new ObservableCollection<string>();
Task.Run(() =>
{
while (!cts.IsCancellationRequested)
{
Content = DateTime.Now.ToString("yyyyMMddHHmmssffff");
App.Current.Dispatcher.BeginInvoke((Action)delegate
{
ContentOb.Add(Content);
});
System.Diagnostics.Debug.WriteLine(Content);
}
},cts.Token);
}

Wpf Dispatcher.BeginInvoke((Action)delegate{}));的更多相关文章

  1. WPF Dispatcher.BeginInvoke子线程更新UI

    在开发WPF应用时出现:”调用线程无法访问此对象,因为另一个线程拥有该对象.“ 是因为UI线程是WPF应用的主线程,若尝试子线程更新UI线程应使用Dispatcher.BeginInvoke()或者I ...

  2. Dispatcher.BeginInvoke()方法使用不当导致UI界面卡死的原因分析

    原文:Dispatcher.BeginInvoke()方法使用不当导致UI界面卡死的原因分析 前段时间,公司同事开发了一个小工具,在工具执行过程中,UI界面一直处于卡死状态. 通过阅读代码发现,主要是 ...

  3. WPF子线程更新UI(Dispatcher.BeginInvoke)

       在做WPF开发时,如果直接在子线程里更新UI会报错—–“调用线程无法访问此对象,因为另一个线程拥有该对象.”,这是因为WPF禁止在非UI线程里直接更新UI界面. 解决方案:   在子线程里调用D ...

  4. WPF Dispatcher 一次小重构

    几个月之前因为项目需要,需要实现一个类似于WPF Dispatcher类的类,来实现一些线程的调度.之前因为一直做Asp.Net,根本没有钻到这个层次去,做的过程中,诸多不顺,重构了四五次,终于实现, ...

  5. 深入了解 WPF Dispatcher 的工作原理(Invoke/InvokeAsync 部分)

    深耕 WPF 开发的各位程序员大大们一定避不开使用 Dispatcher.跨线程访问 UI 当然免不了用到它,将某个任务延迟到当前任务之后执行也会用到它.Dispatcher.Invoke.Dispa ...

  6. WPF Dispatcher的使用

     <Window x:Class="DispatcherExam.MainWindow"         xmlns="http://schemas.micro ...

  7. WPF Dispatcher介绍

    微软在WPF引入了Dispatcher,那么这个Dispatcher的主要作用是什么呢?Dispatcher的作用是用于管理线程工作项队列.主线程负责接收输入.处理事件.绘制屏幕等工作,这样一来,UI ...

  8. WPF Dispatcher使用

    微软在WPF引入了Dispatcher,那么这个Dispatcher的主要作用是什么呢?Dispatcher的作用是用于管理线程工作项队列.主线程负责接收输入.处理事件.绘制屏幕等工作,这样一来,UI ...

  9. System.Windows.Application.Current.Dispatcher.BeginInvoke

    System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>                        ...

随机推荐

  1. 简单使用一下IDEA 的HTTP Client

    前言 只有光头才能变强. 文本已收录至我的GitHub精选文章,欢迎Star:https://github.com/ZhongFuCheng3y/3y 相信大家都用过POSTMAN吧,后端在开发的时候 ...

  2. CentOS7.2下部署zabbix4.0

    整体部署采用centos7+php+apache+mariadb 基础环境配置优化 1. 关闭防火墙 [root@monitor_53 ~]$ systemctl stop firewalld [ro ...

  3. IPFS学习-IPNS

    星际名称系统(IPNS)是一个创建个更新可变的链接到IPFS内容的系统,由于对象在IPFS中是内容寻址的,他们的内容变化将导致地址随之变化.对于多变的事物是有用的.但是很难获取某些内容的最新版本. 在 ...

  4. 使用Power BI Desktop 制作并发布到Power BI 服务,使用Power BI Mobile查询报表

    上节内容中,我们介绍了Power BI的基本概念,本节我们分享以下一个简单报表从使用Power BI Desktop制作,到发布到Power BI 服务,到从Power BI Mobile上查阅报表的 ...

  5. Sql: Oracle paging

    --书分类目录kind --涂聚文 Geovin Du create table geovindu.BookKindList ( BookKindID INT PRIMARY KEY, BookKin ...

  6. 使用ReentrantLock

    /** * java.util.concurrent.locks包提供的ReentrantLock用于替代synchronized加锁* 因为synchronized是Java语言层面提供的语法,所以 ...

  7. IT兄弟连 HTML5教程 CSS3属性特效 3D变换1

    3D变换较2D变换多了一下的转换属性,3D转换属性及描述如表1: 表1  3D转换属性 3D的转换方法如表2: 表2  3D转换方法     1  transform-style transform- ...

  8. 关于java基础、多线程、JavaWeb基础、数据库、SSM、Springboot技术汇总

    作者 : Stanley 罗昊 本人自行总结,纯手打,有疑问请在评论区留言 [转载请注明出处和署名,谢谢!] 一.java基础 1.多态有哪些体现形式? 重写.重载 2. Overriding的是什么 ...

  9. 这7个npm命令将帮助您节省时间

    作为JavaScript开发人员,NPM是我们一直使用的东西,并且我们的脚本在终端上连续运行. 如果我们可以节省一些时间呢? 1.直接从npm打开文档 如果我们可以直接使用npm跳转到软件包的文档怎么 ...

  10. 通过pipeline实现jenkins的ci/cd功能

    pipeline是基于groove进行实现的,不过从jenkins官方的说明中,pipeline分为脚本式和声明式,参见链接.经过对两种的比较,个人比较偏向脚本式的方法.也就是 Jenkinsfile ...