ThreadPoolTimer -延迟执行, 周期执行
介绍
重新想象 Windows 8 Store Apps 之 线程池
- 通过 ThreadPoolTimer 实现延迟执行
- 通过 ThreadPoolTimer 实现周期执行
- 通过 ThreadPool 实现“在线程池中找一个线程去执行指定的方法”
示例
1、通过 ThreadPoolTimer 实现延迟执行(ThreadPoolTimer 在 Windows.System.Threading 命名空间下)
Thread/ThreadPool/DelayTimer.xaml

<Page
x:Class="XamlDemo.Thread.ThreadPool.DelayTimer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Thread.ThreadPool"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" /> <Button Name="btnCreateDelay" Content="延迟 3 秒后执行一个任务" Click="btnCreateDelay_Click_1" Margin="0 10 0 0" /> <Button Name="btnCancelDelay" Content="取消任务" Click="btnCancelDelay_Click_1" Margin="0 10 0 0" /> </StackPanel>
</Grid>
</Page>

Thread/ThreadPool/DelayTimer.xaml.cs

/*
* 通过 ThreadPoolTimer 实现延迟执行(ThreadPoolTimer 在 Windows.System.Threading 命名空间下)
*
* ThreadPoolTimer - 计时器
* ThreadPoolTimer CreateTimer(TimerElapsedHandler handler, TimeSpan delay, TimerDestroyedHandler destroyed); - 创建一个用于延迟执行的计时器
* handler - 指定的延迟时间过后,所需要执行的方法
* delay - 延迟时间
* destroyed - 当 ThreadPoolTimer 完成了自身的使命后所执行的方法(比如延迟方法执行完了或计时器被取消了)
* Cancel() - 取消计时器
* Delay - 延迟时间,只读
*/ using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.System.Threading;
using Windows.UI.Core; namespace XamlDemo.Thread.ThreadPool
{
public sealed partial class DelayTimer : Page
{
private ThreadPoolTimer _timer; public DelayTimer()
{
this.InitializeComponent();
} // 创建一个延迟计时器
private void btnCreateDelay_Click_1(object sender, RoutedEventArgs e)
{
_timer = ThreadPoolTimer.CreateTimer(
(timer) =>
{
var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
lblMsg.Text = "任务执行了";
});
},
TimeSpan.FromSeconds(3),
(timer) =>
{
var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
lblMsg.Text += Environment.NewLine;
lblMsg.Text += "ThreadPoolTimer 的使命结束了";
});
}); lblMsg.Text = "延迟 3 秒后执行一个任务";
} // 取消计时器
private void btnCancelDelay_Click_1(object sender, RoutedEventArgs e)
{
if (_timer != null)
{
_timer.Cancel();
_timer = null; lblMsg.Text += Environment.NewLine;
lblMsg.Text += "任务取消了";
}
}
}
}

2、通过 ThreadPoolTimer 实现周期执行(ThreadPoolTimer 在 Windows.System.Threading 命名空间下)
Thread/ThreadPool/PeriodicTimer.xaml

<Page
x:Class="XamlDemo.Thread.ThreadPool.PeriodicTimer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Thread.ThreadPool"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" /> <Button Name="btnCreatePeriodic" Content="执行一个周期任务" Click="btnCreatePeriodic_Click_1" Margin="0 10 0 0" /> <Button Name="btnCancelPeriodic" Content="取消任务" Click="btnCancelPeriodic_Click_1" Margin="0 10 0 0" /> </StackPanel>
</Grid>
</Page>

Thread/ThreadPool/PeriodicTimer.xaml.cs

/*
* 通过 ThreadPoolTimer 实现周期执行(ThreadPoolTimer 在 Windows.System.Threading 命名空间下)
*
* ThreadPoolTimer - 计时器
* ThreadPoolTimer CreatePeriodicTimer(TimerElapsedHandler handler, TimeSpan period, TimerDestroyedHandler destroyed) - 创建一个用于延迟执行的计时器
* handler - 每个周期时间点到达之后,所需要执行的方法
* period - 周期执行的间隔时间
* destroyed - 当 ThreadPoolTimer 完成了自身的使命后所执行的方法(比如计时器被取消了)
* Cancel() - 取消计时器
* Period - 间隔时间,只读
*/ using System;
using Windows.System.Threading;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace XamlDemo.Thread.ThreadPool
{
public sealed partial class PeriodicTimer : Page
{
private ThreadPoolTimer _timer;
private int _periodicTimerCount = 0; public PeriodicTimer()
{
this.InitializeComponent();
} // 创建一个周期计时器
private void btnCreatePeriodic_Click_1(object sender, RoutedEventArgs e)
{
_timer = ThreadPoolTimer.CreatePeriodicTimer(
(timer) =>
{
_periodicTimerCount++; var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
lblMsg.Text = "任务执行次数:" + _periodicTimerCount.ToString();
});
},
// 第 1 次执行 handler 是在计时器被创建的 100 毫秒之后,然后每 100 毫秒执行一次 handler
// 计时器会保证每 100 毫秒调用一次 handler,而不管上一次 handler 是否已执行完
TimeSpan.FromMilliseconds(100),
(timer) =>
{
var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
lblMsg.Text += Environment.NewLine;
lblMsg.Text += "ThreadPoolTimer 的使命结束了";
});
}); lblMsg.Text = "任务执行次数:0";
} // 取消计时器
private void btnCancelPeriodic_Click_1(object sender, RoutedEventArgs e)
{
if (_timer != null)
{
_timer.Cancel();
_timer = null;
_periodicTimerCount = 0; lblMsg.Text = "任务取消了";
}
}
}
}

3、通过 ThreadPool 实现“在线程池中找一个线程去执行指定的方法”(ThreadPool 在 Windows.System.Threading 命名空间下)
Thread/ThreadPool/WorkItem.xaml

<Page
x:Class="XamlDemo.Thread.ThreadPool.WorkItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Thread.ThreadPool"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" /> <TextBlock Name="lblProgress" FontSize="14.667" /> <Button Name="btnCreateWorkItem" Content="在线程池中找一个线程去执行指定的方法" Click="btnCreateWorkItem_Click_1" Margin="0 10 0 0" />
<Button Name="btnCancelWorkItem" Content="取消任务" Click="btnCancelWorkItem_Click_1" Margin="0 10 0 0" /> <Button Name="btnCreateWorkItemByAwait" Content="通过 async await 简化“在线程池中找一个线程去执行指定的方法”" Click="btnCreateWorkItemByAwait_Click_1" Margin="0 30 0 0" /> </StackPanel>
</Grid>
</Page>

Thread/ThreadPool/WorkItem.xaml.cs

/*
* 通过 ThreadPool 实现“在线程池中找一个线程去执行指定的方法”(ThreadPool 在 Windows.System.Threading 命名空间下)
*
* ThreadPool - 线程池
* IAsyncAction RunAsync(WorkItemHandler handler, WorkItemPriority priority) - 在线程池中找一个线程去执行指定的方法,并指定其优先级
* handler - 需要调用的方法
* priority - 优先级(Windows.UI.Core.CoreDispatcherPriority 枚举:Low, Normal, High)
*
*
* 注:关于 IAsyncAction 请参见 XamlDemo/Thread/Async 中的说明
*/ using System;
using System.Threading;
using Windows.Foundation;
using Windows.System.Threading;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace XamlDemo.Thread.ThreadPool
{
public sealed partial class WorkItem : Page
{
private IAsyncAction _threadPoolWorkItem;
private ManualResetEvent _sleep = new ManualResetEvent(false); public WorkItem()
{
this.InitializeComponent();
} // 在线程池中找一个线程去执行指定的方法,并指定其优先级
private void btnCreateWorkItem_Click_1(object sender, RoutedEventArgs e)
{
_threadPoolWorkItem = Windows.System.Threading.ThreadPool.RunAsync(
(threadPoolWorkItem) =>
{
int percent = 0; // 用于模拟执行进度(0 - 100)
while (percent < 100)
{
// 当前线程 sleep 100 毫秒
_sleep.WaitOne(100); // 如果 IAsyncAction 被取消了则退出此 handler 的执行
if (threadPoolWorkItem.Status == AsyncStatus.Canceled)
break; percent++; var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
lblProgress.Text = "进度:" + percent.ToString() + "%";
});
}
},
WorkItemPriority.High); // IAsyncAction 完成之后(比如任务完成了或者任务取消了)
// 关于 IAsyncAction 的详细说明请参见 XamlDemo/Thread/Async
_threadPoolWorkItem.Completed = new AsyncActionCompletedHandler(
async (IAsyncAction threadPoolWorkItem, AsyncStatus status) =>
{
await Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
switch (status)
{
case AsyncStatus.Completed:
lblMsg.Text = "任务完成了";
break;
case AsyncStatus.Canceled:
lblMsg.Text = "任务取消了";
break;
case AsyncStatus.Started:
case AsyncStatus.Error:
break;
}
});
}); lblProgress.Text = "进度:0%";
lblMsg.Text = "任务开始了";
} // 取消任务
private void btnCancelWorkItem_Click_1(object sender, RoutedEventArgs e)
{
if (_threadPoolWorkItem != null)
{
_threadPoolWorkItem.Cancel();
_threadPoolWorkItem = null;
}
} // 通过 async await 简化 ThreadPool.RunAsync() 的使用(关于 async 和 await 的详细说明请参见 XamlDemo/Thread/Async)
private async void btnCreateWorkItemByAwait_Click_1(object sender, RoutedEventArgs e)
{
lblProgress.Text = "";
lblMsg.Text = ""; string result = ""; await Windows.System.Threading.ThreadPool.RunAsync(
delegate
{
new ManualResetEvent(false).WaitOne(3000);
result = "在线程池中找一个线程去执行指定的逻辑,然后通过 await 返回 UI 线程";
}); lblMsg.Text = result;
}
}
}
ThreadPoolTimer -延迟执行, 周期执行的更多相关文章
- 重新想象 Windows 8 Store Apps (42) - 多线程之线程池: 延迟执行, 周期执行, 在线程池中找一个线程去执行指定的方法
[源码下载] 重新想象 Windows 8 Store Apps (42) - 多线程之线程池: 延迟执行, 周期执行, 在线程池中找一个线程去执行指定的方法 作者:webabcd 介绍重新想象 Wi ...
- ScheduledThreadPoolExecutor源码分析-你知道定时线程池是如何实现延迟执行和周期执行的吗?
Java版本:8u261. 1 简介 ScheduledThreadPoolExecutor即定时线程池,是用来执行延迟任务或周期性任务的.相比于Timer的单线程,定时线程池在遇到任务抛出异常的时候 ...
- ScheduledExecutorService定时周期执行指定的任务
示例代码 package com.effective.common.concurrent.execute; import java.text.DateFormat; import java.text. ...
- 运行时修改TimerTask的执行周期
java.util.TimerTask类的执行周期period变量的声明如下: /** * Period in milliseconds for repeating tasks. A positive ...
- activity生命周期分析(两个activity之间跳转的生命周期执行顺序)
NoteMainActivity点击跳转至NoteListActivity 我们都了解: 当A界面点击进入B界面时,此时 A===onPause--->onStop ...
- vue父子组件生命周期执行顺序
之前写了vue的生命周期,本以为明白了vue实例在创建到显示在页面上以及销毁等一系列过程,以及各个生命周期的特点.然而今天被问到父子组件生命周期执行顺序的时候一头雾水,根本不知道怎么回事.然后写了一段 ...
- React生命周期执行顺序详解
文章内容转载于https://www.cnblogs.com/faith3/p/9216165.html 一.组件生命周期的执行次数是什么样子的??? 只执行一次: constructor.compo ...
- js多次触发事件,在一定延迟内只执行一次 (事件累加)
js多次触发事件,在一定延迟内只执行一次的案例: <!DOCTYPE html> <html> <head> <meta charset="UTF- ...
- 【 PostgreSQL】后台周期执行函数实例(shell+crontab)
工作中常见函数后台周期执行的情况,Oracle有job实现,gp数据库可以通过shell+crontab实现.流程如下: gpadmin用户下创建函数sh脚本. 将sh挂在crontab任务上 ### ...
随机推荐
- springboot 学习资源推荐
springboot 是什么?对于构建生产就绪的Spring应用程序有一个看法. Spring Boot优先于配置的惯例,旨在让您尽快启动和运行.(这是springboot的官方介绍) 我们为什么要学 ...
- Delphi_09_Delphi_Object_Pascal_面向对象编程
今天这里讨论一下Delphi中的面向对象编程,这里不做过多过细的讨论,主要做提纲挈领的描述,帮助自己抓做重点. 本随笔分为两部分: 一.面向对象编程 二.面向对象编程详细描述 ------------ ...
- 你必须知道的Microsoft SQL Server一
不知道为什么我Win10环境下安装的Sqlserver2012,智能提示的功能基本上没有用,没办法,我还是选择安装插件SQL Prompt 5吧.下载地址:http://www.uzzf.com/so ...
- [deviceone开发]-Star分享的优惠券商户管理端App开源
一.简介 这是一个优惠券的商主端,也就是配置发送优惠券的App 页面和交互还是像纳豆那样非常漂亮流畅,大家可以参考一下二.效果图 三.相关下载 https://github.com/do-projec ...
- JQuery中隐藏/显示事件函数
1.$("button").click(function(){ $("p").hide(); });2.如果您的网站包含许多页面,并且您希望您的 jQuery ...
- 商业智能BI推动制造业智能化转型
制造业是我国国民经济的支柱产业,是我国经济增长的主导部门和经济转型的基础,如今我国制造业面临技术工艺不精.缺乏市场意识.商贸流通环节多.物流成本大.仓储效率低下等问题,正处在转型的特殊时期. 内忧: ...
- Dynamics CRM 之ADFS 使用 SQL Server 的联合服务器场
此拓扑用于 Active Directory 联合身份验证服务 (AD FS) 不同于使用 Windows 内部数据库 (WID) 部署拓扑,因为不会将数据复制到每台联合服务器场中的联合身份验证服务器 ...
- 如何使用VS在SharePont 2013中插入ashx文件
http://www.lifeonplanetgroove.com/adding-and-deploying-generic-handlers-ashx-to-a-sharepoint-2010-vi ...
- centos 6 YUM安装 lmp
准备篇: 1.配置防火墙,开启80端口.3306端口 vi /etc/sysconfig/iptables -A INPUT -m state --state NEW -m t ...
- 01背包问题python 2.7实现
版权声明:本文为博主原创文章,转载请注明转自 http://www.cnblogs.com/kdxb/p/6140625.html #!/usr/bin/env python # -*- coding ...