C# 任务和返回任务的函数之间的差异

C# 任务和返回任务的函数之间的差异,c#,C#,嗨,我知道我们可以像这样用c运行任务 Task t1 = new Task(new Action(A)) 但A是静态函数 我们可以有非静态函数吗?当我们有返回任务的函数时 我们能像这样跑吗 new Task(new Action(A)); 如果我们做不到,那两者之间是什么 static void A() { Console.Write("task"); } Task t1 = new Task(new Action(A)); 及 公共异步任务集\u映像(

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

Task t1 = new Task(new Action(A))
但A是静态函数
我们可以有非静态函数吗?当我们有返回任务的函数时 我们能像这样跑吗

new Task(new Action(A));
如果我们做不到,那两者之间是什么

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

公共异步任务集\u映像(字符串位置\u在\u服务器中,字符串位置\u保存,字符串名称\u文件)
{
Ntaban.Api.Api_HttpClient apic=新的Ntaban.Api.Api_HttpClient();
字符串位置=要保存的位置+名称文件;
字符串location\u directory=要保存的位置;
if(Directory.Exists(location_Directory)==false)
{
CreateDirectory(位置\目录);
}
if(File.Exists(location)==false)
{
等待apic。下载\u文件\u异步(\u服务器中的位置\u+名称\u文件,位置,空);
}
BitmapImage s1=新的BitmapImage();
s1.BeginInit();
s1.UriSource=new System.Uri(保存位置+名称文件);
s1.EndInit();
返回s1;
}
imgProfile.Source=savefile.Set_Image(Ntaban.Api.Api_server.Host+“/content/profile/”,St_Major.Directory.Directory_Main,lst.First().picAdr)。结果;
我知道我们可以像这样用c运行任务

这实际上并没有运行任务。它创建一个准备运行但尚未实际计划的任务

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

两者之间是什么

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


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

我知道这一点,但当我们有返回任务的函数时(例如),它将作为任务运行。换句话说,我喜欢在任务、线程或cpu的其他核心中运行我的函数。我们应该怎么做?@amirjahany:如果你想在线程池中运行代码,那么就使用
task.run
。谢谢你的回答。你能告诉我关于threadpool的事吗?我听不懂it@amirjahany:没有,但是你可以读到。
  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;