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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM