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.

  • 相关阅读:
    关于ACID,BASE和CAP定理的探究
    2020年10月3日——武汉,成都,南京房价揭秘
    程序员如何选择自己的保险
    Yarn系列(一)——Yarn整体介绍
    利用媒体查询实现响应式布局
    移动端web布局:适配
    scss在编辑器中保存自动编译css插件及安装
    移动端web布局:像素与成像的基本原理
    微信小程序:路由
    自定义vue指令
  • 原文地址:https://www.cnblogs.com/grj001/p/12224564.html
Copyright © 2011-2022 走看看