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 - 100)
while (percent < )
{
// 当前线程 sleep 100 毫秒
_sleep.WaitOne();
// 如果 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();
result = "在线程池中找一个线程去执行指定的逻辑,然后通过 await 返回 UI 线程";
});
lblMsg.Text = result;
}
}