赞
踩
WPF异步任务
主界面
- //打印的内容:文本框显示的内容
- public string PrintNumbers
- {
- get { return printNumbers; }
- set
- {
- printNumbers = value;
- RaisePropertyChanged();
- }
- }
- <TextBox Name="Execution" HorizontalAlignment="Right"
- Height="649" Margin="0,10,10,0" TextWrapping="Wrap"
- ScrollViewer.HorizontalScrollBarVisibility="Visible"
- ScrollViewer.VerticalScrollBarVisibility="Auto"
- Text="{Binding PrintNumbers,Mode=TwoWay,
- UpdateSourceTrigger=PropertyChanged}"
- VerticalAlignment="Top" Width="692" Grid.Column="1" />
在视图模型中定义命令:
- //绑定的命令
- public ICommand StartButtonCommand { get; set; }
- public ICommand AddTaskCommand { get; set; }
- public ICommand ClearAllData { get; set; }
在主界面xaml中绑定命令:
- <Button Content="Start Task" Height="36"
- Margin="10,30,797,0"
- VerticalAlignment="Top"
- Width="119" Command="{Binding StartButtonCommand}" Grid.Column="1"/>
创建命令实例:
- StartButtonCommand = new DelegateCommand(TaskExecutionOrder);
- AddTaskCommand = new DelegateCommand(SelectedTaskExecution);
- ClearAllData = new DelegateCommand(ClearData);
- //radiobutton绑定的属性
- public bool IsOddChecked //选择奇数属性
- {
- get { return isOddChecked; }
- set { SetProperty(ref isOddChecked, value); RaisePropertyChanged(); }
- }
- //radiobutton绑定的属性
- public bool IsEvenChecked//选择偶数属性
- {
- get { return isEvenChecked; }
- set { SetProperty(ref isEvenChecked, value); RaisePropertyChanged(); }
- }
- <RadioButton x:Name="chckOddNum" Content="OddNumbers"
- HorizontalAlignment="Left" Margin="10,413,0,0"
- VerticalAlignment="Top"
- IsChecked="{Binding IsOddChecked,Mode=TwoWay,
- UpdateSourceTrigger=PropertyChanged}" Height="44" Width="119" RenderTransformOrigin="1,0.546" Grid.Column="1"/>
- private static Queue<Action> queue = new Queue<Action>();//操作队列
- private static readonly object queuelock = new object();//队列锁
Task.Run(() => ExecuteTasks());//执行异步任务,从队列中取出任务动作
- //开始按钮执行异步任务
- private async void ExecuteTasks()
- {
-
- while (true)
- {
- Action task = null;
- lock (queuelock)
- {
- if (queue.Count > 0)
- {
- task = queue.Dequeue();//取出一个任务操作
- }
- }
- if (task != null)
- {
- await Task.Run(() =>
- {
- task.Invoke();
- Thread.Sleep(100);
- });
- }
-
- }
- }
- //开始按钮委托命令 :执行 奇数、偶数任务
- public void TaskExecutionOrder()
- {
- queue.Enqueue(OddNumbers);
- queue.Enqueue(EvenNumbers);
- taskCount = queue.Count;//任务数
- }
- //奇数任务操作
- private void OddNumbers()
- {
- Dispatcher.CurrentDispatcher.Invoke(() =>
- {
- this.PrintNumbers += Environment.NewLine;
- this.PrintNumbers += Environment.NewLine;
- this.PrintNumbers += "OddNumbers between 1 to 100" + Environment.NewLine + "Task:" + " " + taskNumber.ToString();
- this.PrintNumbers += Environment.NewLine;
- this.ExecutionOrder += "Task:" + taskNumber.ToString() + "-Started" + "\n";
-
- });
- for (int i = 0; i <= 100; i++)
- {
-
- Dispatcher.CurrentDispatcher.Invoke(() =>
- {
- if (i % 2 != 0)//奇数
- {
- this.PrintNumbers += i.ToString() + " "; //属性改变,触发UI更新
-
- Thread.Sleep(10);
- }
-
- });
-
- }
-
- this.ExecutionOrder += "Task:" + taskNumber.ToString() + "-Stopped" + "\n";
- taskNumber++;//下一任务号
- Thread.Sleep(1000);
-
- }
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="53*"/>
- <ColumnDefinition Width="739*"/>
- </Grid.ColumnDefinitions>
- <TextBox Name="Execution" HorizontalAlignment="Right"
- Height="649" Margin="0,10,10,0" TextWrapping="Wrap"
- ScrollViewer.HorizontalScrollBarVisibility="Visible"
- ScrollViewer.VerticalScrollBarVisibility="Auto"
- Text="{Binding PrintNumbers,Mode=TwoWay,
- UpdateSourceTrigger=PropertyChanged}"
- VerticalAlignment="Top" Width="692" Grid.Column="1" />
-
- <Button Content="Start Task" Height="36"
- Margin="10,30,797,0"
- VerticalAlignment="Top"
- Width="119" Command="{Binding StartButtonCommand}" Grid.Column="1"/>
-
- <RadioButton x:Name="chckOddNum" Content="OddNumbers"
- HorizontalAlignment="Left" Margin="10,413,0,0"
- VerticalAlignment="Top"
- IsChecked="{Binding IsOddChecked,Mode=TwoWay,
- UpdateSourceTrigger=PropertyChanged}" Height="44" Width="119" RenderTransformOrigin="1,0.546" Grid.Column="1"/>
-
- <RadioButton x:Name="chckEvenNum" Content="EvenNumbers"
- HorizontalAlignment="Left" Margin="10,462,0,0"
- VerticalAlignment="Top" IsChecked="{Binding IsEvenChecked,
- Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Height="42" Width="119" Grid.Column="1"/>
-
- <Button Content="Add Task" Height="31" HorizontalAlignment="Left"
- Margin="10,543,0,0" VerticalAlignment="Top" Width="119"
- Command="{Binding AddTaskCommand}" Grid.Column="1"/>
-
- <TextBox HorizontalAlignment="Left" Height="296"
- VerticalScrollBarVisibility="Auto"
- HorizontalScrollBarVisibility="Auto" Margin="31,88,0,0"
- VerticalAlignment="Top" Width="216"
- Text="{Binding ExecutionOrder,UpdateSourceTrigger=PropertyChanged}" Grid.ColumnSpan="2"/>
-
- <Button Content="ClearAll" HorizontalAlignment="Left" Margin="10,604,0,0"
- VerticalAlignment="Top" Command="{Binding ClearAllData,
- UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Width="119"
- Height="30" Grid.Column="1"/>
- </Grid>
- namespace MultiThreadingWPF
- {
- using Prism.Commands;
- using Prism.Mvvm;
- using System;
- using System.Collections.Generic;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows.Input;
- using System.Windows.Threading;
- using MultiThreadingWPF.Model;
-
- public class MainWindowViewModel : BindableBase
- {
-
- private static Queue<Action> queue = new Queue<Action>();//操作队列
- private static readonly object queuelock = new object();//队列锁
-
- private string printNumbers;//打印的数字
- private string taskName;//任务名
- private static int taskNumber = 1;//任务号
-
- private TaskModel __taskModel;//任务模型 未使用
-
- private string executionOrder;// 执行订单
-
- private bool isOddChecked;//奇数选择字段
- private bool isEvenChecked;//偶数选择字段
- //绑定的命令
- public ICommand StartButtonCommand { get; set; }
- public ICommand AddTaskCommand { get; set; }
- public ICommand ClearAllData { get; set; }
- //任务数
- private int taskCount;
- //未使用TaskModel
- public TaskModel TasksModel
- {
- get { return __taskModel; }
- set { SetProperty(ref __taskModel, value); RaisePropertyChanged(); }
- }
-
- public string ExecutionOrder//
- {
- get { return executionOrder; }
- set { SetProperty(ref executionOrder, value); RaisePropertyChanged(); }
- }
- //radiobutton绑定的属性
- public bool IsOddChecked //选择奇数属性
- {
- get { return isOddChecked; }
- set { SetProperty(ref isOddChecked, value); RaisePropertyChanged(); }
- }
- //radiobutton绑定的属性
- public bool IsEvenChecked//选择偶数属性
- {
- get { return isEvenChecked; }
- set { SetProperty(ref isEvenChecked, value); RaisePropertyChanged(); }
- }
- //任务名
- public string TaskName
- {
- get { return taskName; }
- set
- {
- taskName = value;
- RaisePropertyChanged();
- }
- }
- //打印的内容:文本框显示的内容
- public string PrintNumbers
- {
- get { return printNumbers; }
- set
- {
- printNumbers = value;
- RaisePropertyChanged();
- }
- }
- //任务数
- public int TaskCount
- {
- get { return taskCount; }
- set { taskCount = value; RaisePropertyChanged(); }
- }
- //主窗体视图模型
- public MainWindowViewModel()
- {
- TasksModel = new TaskModel();
- StartButtonCommand = new DelegateCommand(TaskExecutionOrder);
- AddTaskCommand = new DelegateCommand(SelectedTaskExecution);
- ClearAllData = new DelegateCommand(ClearData);
- Task.Run(() => ExecuteTasks());
- }
- //添加(选择的radiobuttion)任务按钮 委托命令
- private void SelectedTaskExecution()
- {
- if(isEvenChecked)
- {
- Task.Run(()=>EvenNumbers());
- }
- else if(isOddChecked)
- {
- Task.Run(()=>OddNumbers());
- }
- else
- {
- this.PrintNumbers += "Please select any one Task to be executed"+"\n";
- }
- }
- //开始按钮委托命令 :执行 奇数、偶数任务
- public void TaskExecutionOrder()
- {
- queue.Enqueue(OddNumbers);
- queue.Enqueue(EvenNumbers);
- taskCount = queue.Count;
- }
- //开始按钮执行异步任务
- private async void ExecuteTasks()
- {
-
- while (true)
- {
- Action task = null;
- lock (queuelock)
- {
- if (queue.Count > 0)
- {
- task = queue.Dequeue();//取出一个任务操作
- }
- }
- if (task != null)
- {
- await Task.Run(() =>
- {
- task.Invoke();
- Thread.Sleep(100);
- });
- }
-
- }
- }
- //偶数任务操作
- private void EvenNumbers()
- { //线程池线程 调用UI控件绑定属性
- Dispatcher.CurrentDispatcher.Invoke(() =>
- {
- this.PrintNumbers += Environment.NewLine;
- this.PrintNumbers += Environment.NewLine;
- this.PrintNumbers += "EvenNumbers between 1 to 100" + Environment.NewLine + "Task:" + " " + taskNumber.ToString();
- this.PrintNumbers += Environment.NewLine;
- this.ExecutionOrder += "Task:" + taskNumber.ToString() + "-Started " + "\n";
-
- });
-
- for (int i = 0; i <= 100; i++)//偶数
- {
- Dispatcher.CurrentDispatcher.Invoke(() =>
- {
- if (i % 2 == 0)
- {
- this.PrintNumbers += i.ToString() + " ";
- Thread.Sleep(10);
- }
- });
- }
-
- this.ExecutionOrder += "Task:" + taskNumber.ToString() + "-Stopped" + "\n";
- taskNumber++;
- Thread.Sleep(1000);
- }
- //奇数任务操作
- private void OddNumbers()
- {
- Dispatcher.CurrentDispatcher.Invoke(() =>
- {
- this.PrintNumbers += Environment.NewLine;
- this.PrintNumbers += Environment.NewLine;
- this.PrintNumbers += "OddNumbers between 1 to 100" + Environment.NewLine + "Task:" + " " + taskNumber.ToString();
- this.PrintNumbers += Environment.NewLine;
- this.ExecutionOrder += "Task:" + taskNumber.ToString() + "-Started" + "\n";
-
- });
- for (int i = 0; i <= 100; i++)
- {
-
- Dispatcher.CurrentDispatcher.Invoke(() =>
- {
- if (i % 2 != 0)//奇数
- {
- this.PrintNumbers += i.ToString() + " ";
-
- Thread.Sleep(10);
- }
-
- });
-
- }
-
- this.ExecutionOrder += "Task:" + taskNumber.ToString() + "-Stopped" + "\n";
- taskNumber++;//下一任务号
- Thread.Sleep(1000);
-
- }
- //清空按钮 委托命令
- private void ClearData()
- {
- PrintNumbers = string.Empty;//文本框显示的内容
-
- }
-
- }
- }
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace MultiThreadingWPF.Model
- {
- public class TaskModel : INotifyPropertyChanged
- {
- private string TaskName { get; set; } //任务名
- private string PrintNumbers { get; set; } //打印的字符串
-
- public event PropertyChangedEventHandler PropertyChanged; //属性改变事件
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。