zoukankan      html  css  js  c++  java
  • C# Task启动带参数和返回值的函数任务

    c# Task启动带参数和返回值的函数任务

    Task有时候相当于Thread的作用

    下面的例子test2 是个带参数和返回值的函数。

    private int test2(object i){
       this.Invoke(new Action(()=>{pictureBox1.Visible=true;}));
       System.Threading.Thread.Sleep(3000);
       MessageBox.Show("hello:"+ i);
       this.Invoke(new Action(()=>{pictureBox1.Visible=false;}));
       return 0;
    }

    //测试调用
    private void call(){

            //Func<string, string> funcOne = delegate(string s){  return "fff"; };
            object  i=55;
            var t= Task<int>.Factory.StartNew(new Func<object ,int>(test2),i);

    }

    ===========下载网站源文件例子==================================

    HttpClient 引用System.Net.Http

    private async Task< int> test2(object i){
    this.Invoke(new Action(()=>{pictureBox1.Visible=true;}));

       HttpClient client= new HttpClient();
           var a= await     client.GetAsync("http://www.baidu.com");
          Task<string> s=  a.Content.ReadAsStringAsync();
          MessageBox.Show (s.Result);
            
            //System.Threading.Thread.Sleep(3000);
            //MessageBox.Show("hello:"+ i);
            this.Invoke(new Action(()=>{pictureBox1.Visible=false;}));
            return 0;
        }
        
        
    async   private  void call(){
            
            //Func<string, string> funcOne = delegate(string s){  return "fff"; };
            object  i=55;
            var t= Task<Task<int>>.Factory.StartNew(new Func<object ,Task<int>>(test2),i);
    
    
    
    
        }

    ---------------或者---------

        private async void  test2(){
            this.Invoke(new Action(()=>{pictureBox1.Visible=true;}));       
            HttpClient client= new HttpClient();
            var a= await    client.GetAsync("http://www.baidu.com");
            Task<string> s=  a.Content.ReadAsStringAsync();
            MessageBox.Show (s.Result);
            this.Invoke(new Action(()=>{pictureBox1.Visible=false;}));
    
        }
        
        
        private  void call(){
            
            var t= Task.Run(new Action(test2));
                       
            //相当于
            //Thread th= new Thread(new ThreadStart(test2));
            //th.Start();
    
        }

    fffffffffffffffff

    test red font.

  • 相关阅读:
    VirtualBox4.3.12 安装ubuntu 14.04 分辨率过小(600*480)问题的解决方法
    asp.net 权限管理系统
    rdlc 格式设置
    Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0 异常处理
    Asp.Net Web Forms/MVC/Console App中使用Autofac
    Mysql优化小记1
    Zyan 一个通信框架
    RDLC
    通过.NET客户端异步调用Web API(C#)
    ECharts问题--散点图中对散点添加点击事件
  • 原文地址:https://www.cnblogs.com/grj001/p/12224563.html
Copyright © 2011-2022 走看看