返回任务的任务和功能之间的区别

时间:2017-01-26 13:38:37

标签: c#

嗨,我知道我们可以像这样使用c#运行任务

Task t1 = new Task(new Action(A))

但A是静态功能
我们可以有非静态函数,当我们有返回任务的函数时 我们可以像

一样运行
new Task(new Action(A));

如果我们不知道什么是def之间的

  static void A()
 {
        Console.Write("task");
 }
    Task t1 = new Task(new Action(A));  

  public async Task<BitmapImage> Set_Image(string location_in_server, string location_to_save, string name_file)
        {
            Ntaban.Api.API_HttpClient apic = new Ntaban.Api.API_HttpClient();
        string location = location_to_save + name_file;
        string location_directory = location_to_save;
        if (Directory.Exists(location_directory) == false)
        {
            Directory.CreateDirectory(location_directory);
        }
        if (File.Exists(location) == false)
        {
            await apic.download_file_async(location_in_server + name_file, location, null);
        }
        BitmapImage s1 = new BitmapImage();
        s1.BeginInit();
        s1.UriSource = new System.Uri(location_to_save + name_file);
        s1.EndInit();
        return s1;
    }
  imgProfile.Source = savefile.Set_Image(Ntaban.Api.API_server.Host + "/content/profile/", St_Major.Directories.Directory_Main, lst.First().picAdr).Result;

1 个答案:

答案 0 :(得分:0)

  

我知道我们可以像这样使用c#运行任务

实际上并没有执行任务。它创建了一个可以运行但尚未实际安排的任务。

哦,你不应该 这样做。实际上没有理由使用Task构造函数。

  

什么是def之间的

任务构造函数创建一个未运行的任务。据推测,未显示的代码会在线程池上安排任务(例如,t1.Start(TaskScheduler.Default)),在这种情况下,它将在线程池线程上执行A

async方法返回的任务表示该方法的执行。请注意,async表示异步任务 - 这是在线程池线程上执行而不是。我有一篇博文,详细介绍how async and await work