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.

原文地址:https://www.cnblogs.com/grj001/p/12224563.html