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.

  • 相关阅读:
    svn命令行使用积累
    linux下编译出现tmp空间不足解决办法
    secure CRT the remote system refused the connection 解决办法
    Makefile 中符合的使用
    函数指针作为某个函数的参数及定义函数指针(回调函数)
    C语言指针变量作为函数参数
    虚拟机下安装ubuntu后root密码登录失败的问题
    管理者需要知道的十大经典理论
    System V 与 POSIX
    带你吃透RTMP
  • 原文地址:https://www.cnblogs.com/grj001/p/12224563.html
Copyright © 2011-2022 走看看