赞
踩
- //新建一个Task
- Task t1 = new Task(() => {
- Console.WriteLine("Task完成!");
- });
- //启动Task
- t1.Start();
-
- Console.WriteLine("UI线程完成!");
- //新建一个Task(Task工厂创建,自动启动)
- Task t1 = Task.Factory.StartNew(() => {
- Console.WriteLine("Task完成!");
- });
-
- Console.WriteLine("UI线程完成!");
- void Test()
- {
- Console.WriteLine("Task完成!");
- }
-
- Action action = new Action(Test);
-
- //新建一个Task
- Task t1 = new Task(action);
- //启动Task
- t1.Start();
-
- Console.WriteLine("UI线程完成!");
- //新建一个Task
- Task t1 = new Task(() => {
- Console.WriteLine("Task完成!");
- });
- //启动Task
- t1.Start();
-
- Console.WriteLine("UI线程开始等待!");//①
-
- t1.Wait();
-
- Console.WriteLine("UI线程完成!");//②
- //新建一个Task
- Task t1 = new Task(() => {
- Console.WriteLine("Task1完成!");
- });
- //新建一个Task
- Task t2 = new Task(() => {
- Console.WriteLine("Task2完成!");
- });
- //启动Task
- t1.Start();
- t2.Start();
-
- Console.WriteLine("UI线程开始等待!");
-
- //等待t1,t2都完成
- Task.WaitAll(t1,t2);
-
- Console.WriteLine("UI线程完成!");
- /// <summary>
- /// 开始一个异步任务
- /// </summary>
- /// <param name="taskAction">异步任务执行委托</param>
- /// <param name="taskEndAction">异步任务执行完毕后的委托(会跳转回UI线程)</param>
- /// <param name="control">UI线程的控件</param>
- public void StartAsyncTask(Action taskAction, Action taskEndAction, Control control)
- {
- if (control == null)
- {
- return;
- }
-
- Task task = new Task(() => {
- try
- {
- taskAction();
-
- //返回UI线程
- control.Invoke(new Action(() =>
- {
- taskEndAction();
- }));
- }
- catch (Exception e)
- {
- MessageBox.Show(e.Message);
- }
- });
-
- task.Start();
- }
-
- /// <summary>
- /// 开始一个延时任务
- /// </summary>
- /// <param name="DelayTime">延时时长(秒)</param>
- /// <param name="taskEndAction">延时时间完毕之后执行的委托(会跳转回UI线程)</param>
- /// <param name="control">UI线程的控件</param>
- public void StartDelayTask(int DelayTime, Action taskEndAction, Control control)
- {
- if (control == null)
- {
- return;
- }
-
- Task task = new Task(() => {
- try
- {
- Thread.Sleep(DelayTime * 1000);
-
- //返回UI线程
- control.Invoke(new Action(() =>
- {
- taskEndAction();
- }));
- }
- catch (Exception e)
- {
- MessageBox.Show(e.Message);
- }
- });
-
- task.Start();
- }
- //显示耗时等待界面(比如一串文字:正在加载,请稍等......)
- WaitPage.ShowWait();
-
- StartAsyncTask(
- () => {
- //进行耗时操作......
- },
- () => {
- //耗时操作完成,隐藏耗时等待界面
- WaitPage.HideWait();
- },
- this);
- Console.WriteLine("我军将在三秒后发起反击!");
-
- StartDelayTask(
- //等待的秒数
- 3,
- () => {
- //等待结束要做的事
- Console.WriteLine("我军开始反击!");
- },
- this);
-
- for (int i = 0; i < 10; i++)
- {
- Console.WriteLine(String.Format("敌军第{0}轮进攻!",i));
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。