【发布时间】:2015-11-17 23:28:09
【问题描述】:
我正在构建一个简单的工具,用于通过用户提供的链接从在线公共 GitHub 存储库下载 .lua 文件。我开始学习异步方法,所以我想测试一下自己。
这是一个控制台应用程序(目前)。最终目标是在 repo 中获取 .lua 文件并询问用户他想要下载哪些文件,但如果我现在连接到 GH,我会很高兴。
我正在使用 Octokit (https://github.com/octokit/octokit.net) 将 GitHub API 集成到 .NET。
这是精简后的代码;我删除了一些不重要的东西:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Octokit;
namespace GetThemLuas
{
class Program
{
static readonly GitHubClient Github = new GitHubClient(new ProductHeaderValue ("Testing123"), new Uri("https://www.github.com/"));
static void Main(string[] args)
{
Console.WriteLine("Welcome to GitHub repo downloader");
GetRepoTry4();
}
private static async void GetRepoTry4()
{
try
{
Console.WriteLine("Searching for data"); //returns here... code below is never ran
var searchResults = await Github.Search.SearchRepo(new SearchRepositoriesRequest("octokit"));
if (searchResults != null)
foreach (var result in searchResults.Items)
Console.WriteLine(result.FullName);
Console.WriteLine("Fetching data...."); //testing search
var myrepo = await Github.Repository.Get("Haacked", "octokit.net");
Console.WriteLine("Done! :)");
Console.WriteLine("Repo loaded successfully!");
Console.WriteLine("Repo owner: " + myrepo.Owner);
Console.WriteLine("Repo ID: " + myrepo.Id);
Console.WriteLine("Repo Date: " + myrepo.CreatedAt);
}
catch (Exception e)
{
Console.WriteLine("Ayyyy... troubles"); //never trigged
Console.WriteLine(e.Message);
}
}
}
}
问题在于 await` 关键字,因为它会终止方法并返回。
我仍在学习异步方法,所以可能我搞砸了,但即使是我的 ReSharper 也说得很好。
我用var 替换了task<T> 的东西。对我来说它接缝没问题,没有警告也没有错误。
我修复了await 问题。现在,当我最终连接到 GH 并尝试获取 repo 时,它在两次调用 GH 时都抛出了异常(首先通过评论然后第二次调用进行了测试)。 e.message 是一些巨大的东西。
我将它记录到一个文件中,它看起来像一个 HTML 文档。这里是 (http://pastebin.com/fxJD1dUb)
【问题讨论】:
-
将
GetRepoTry4();更改为Task.Run(async () => { await GetRepoTry4(); }).Wait();和private static async void GetRepoTry4()更改为private static async Task GetRepoTry4() -
谢谢,我刚刚将 void 更改为 task 并执行了此 GetRepoTry().Wait();还尝试了像您建议的那样令人讨厌的方法,并且效果都很好:)我现在有一个新问题:S要编辑我的帖子
-
我的猜测是您的新问题的根源(实际上不知道新问题是什么),是缺少正确使用的
async Task关键字对。一般来说,所有async方法都需要返回一个Task或Task<T>;所有返回Task或Task<T>的方法都应该是async。此外,您应该尽快将代码放入调度程序并开始使用await。 -
你能举个例子吗?请:S
标签: c# github-api octokit.net