C# 如何使用异步任务方法?

C# 如何使用异步任务方法?,c#,.net,winforms,C#,.net,Winforms,我想从我的gmail帐户中获取所有电子邮件,并在列表框中列出它们。 我不知道如何使用异步任务方法。 如何在构造函数中调用它 我得到一个错误: 错误2参数1:无法从“System.Threading.Tasks.Task”转换为“System.Action”我想知道你为什么这样做,你可以这样称呼它: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin

我想从我的gmail帐户中获取所有电子邮件,并在列表框中列出它们。 我不知道如何使用异步任务方法。 如何在构造函数中调用它

我得到一个错误:


错误2参数1:无法从“System.Threading.Tasks.Task”转换为“System.Action”

我想知道你为什么这样做,你可以这样称呼它:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using System.Threading;
using System.IO;

namespace Google_Gmail
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Task task = new Task(ListLabels());
            task.Start();
            task.Wait();
        }

        public async Task ListLabels()
        {

            UserCredential credential;
            using (var stream = new FileStream("client_secrets_desktop.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                    new[] { GmailService.Scope.GmailReadonly },
                    "user", CancellationToken.None);
            }

            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Gmail Test",
            });

            try
            {
                ListLabelsResponse response = service.Users.Labels.List("me").Execute();
                foreach (Google.Apis.Gmail.v1.Data.Label label in response.Labels.OrderBy(p => p.Name))
                {
                    Console.WriteLine(label.Id + " - " + label.Name);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: " + e.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
并从窗体的构造函数中调用这个start方法。

试试这个

 public async void Start()
 {
     Task task = ListLabels().ContinueWith(task1 =>
     {
         //control returns to here
     }, TaskScheduler.FromCurrentSynchronizationContext());
 }

这就是全部

不要使用
新任务
,而是使用
任务。运行
,启动线程并立即调用
Wait()
,为什么不在?ListLabels().Wait()上调用
Wait()
的线程上执行工作呢;正在工作
public async Task ListLabels()
{
    //your code...
}


private void Form1_Load(object sender, EventArgs e)
{
    await ListLabels();
    //more code...
}