zoukankan      html  css  js  c++  java
  • C#执行异步操作的几种方式

    //线程异步按钮

    private void ThreadButton_Click(object sender, RoutedEventArgs e)
    {
    new Thread(o =>
    {
    var time = TestTask();
    Dispatcher.BeginInvoke(DispatcherPriority.Normal,
    new Action<Button, int>(OutputInfo), sender as Button, time);
    })
    { IsBackground = true }
    .Start();
    }

    //线程池异步按钮

    private void ThreadPoolButton_Click(object sender, RoutedEventArgs e)
    {
    ThreadPool.QueueUserWorkItem(s =>
    {
    var time = TestTask();
    Dispatcher.BeginInvoke(DispatcherPriority.Normal,
    new Action<Button, int>(OutputInfo), sender as Button, time);
    });
    }

    //Task异步按钮

    private void TaskButton_Click(object sender, RoutedEventArgs e)
    {
    var t = new Task<int>(TestTask);
    t.ContinueWith(p =>
    {
    Dispatcher.BeginInvoke(DispatcherPriority.Normal,
    new Action<Button, int>(OutputInfo), sender as Button, p.Result);
    });
    t.Start();
    }

    //await异步按钮

    private async void AwaitButton_Click(object sender, RoutedEventArgs e)
    {
    Task<int> t = new Task<int>(TestTask);
    t.Start();
    var time = await t;
    OutputInfo(sender as Button, time);
    //var time = await TestTaskAsync();
    //OutputInfo(sender as Button, time);
    }

    //线程异步性能测试

    private void ThreadTest_Click(object sender, RoutedEventArgs e)
    {
    var time = AsyncTest(new Action(() => ThreadButton_Click(ThreadButton, null)));
    ShowTestResult(sender, time);
    }

    //线程池异步性能测试

    private void ThreadPoolTest_Click(object sender, RoutedEventArgs e)
    {
    var time = AsyncTest(new Action(() => ThreadPoolButton_Click(ThreadPoolButton, null)));
    ShowTestResult(sender, time);
    }

    //Task异步性能测试

    private void TaskTest_Click(object sender, RoutedEventArgs e)
    {
    var time = AsyncTest(new Action(()=> TaskButton_Click(TaskButton, null)));
    ShowTestResult(sender, time);
    }

    //await异步性能测试

    private void AwaitTest_Click(object sender, RoutedEventArgs e)
    {
    var time = AsyncTest(new Action(() => AwaitButton_Click(AwaitButton,null)));
    ShowTestResult(sender, time);
    }
  • 相关阅读:
    [转]SVN服务器搭建和使用(二)
    [转]SVN服务器搭建和使用(一)
    BZOJ 2049 Sdoi2008 Cave 洞穴勘测
    BZOJ 1589 Usaco2008 Dec Trick or Treat on the Farm 采集糖果
    BZOJ 2796 POI2012 Fibonacci Representation
    BZOJ 2115 Wc2011 Xor
    BZOJ 3105 CQOI2013 新Nim游戏
    BZOJ 2460 Beijing2011 元素
    BZOJ 3687 简单题
    BZOJ 1068 SCOI2008 压缩
  • 原文地址:https://www.cnblogs.com/fyy1003668657/p/10839004.html
Copyright © 2011-2022 走看看