后台工作者具有错误的返回类型

时间:2015-08-10 12:26:55

标签: c# async-await task backgroundworker

拥有以下代码:

private async Task backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    UserCredential credential;
    using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
    {
        credential = await GoogleWebAuthorizationBroker.AuthorizeAsync (
        GoogleClientSecrets.Load(stream).Secrets,
        new[] { YouTubeService.Scope.Youtube },
        "user",
        CancellationToken.None,
        new FileDataStore(this.GetType().ToString())
        );
    }

    var youtubeService = new YouTubeService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = this.GetType().ToString()
    });

    PlaylistsResource.ListRequest request = youtubeService.Playlists.List("snippet");
    request.Mine = true;
    PlayListResponse = request.Execute();

}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    MessageBox.Show("OK");
}

当我构建解决方案时,我得到:

'System.Threading.Tasks.Task YouTubeDesktopPlayer.Form1.backgroundWorker1_DoWork(object, System.ComponentModel.DoWorkEventArgs)' has the wrong return type

如何更改退货类型?我有点困惑,我不明白async Task如何使用BackgroundWorker

1 个答案:

答案 0 :(得分:3)

使用split=function(x){ { n=as.numeric(strsplit(as.character(b), "")[[1]]) } 事件处理程序。它会在async void DoWork完成之前触发RunWorkerCompleted,并且不会正确捕获异常。

如果您需要在后台线程上进行异步工作(很少见),请改用DoWork。我有一个blog series详细说明,但要点是:

Task.Run