我实际上是新来的。我有一个简短的应用程序,只是检查该应用程序是否可以从youtube异步获取身份验证,然后将应用程序返回到它的轨道。这是我的代码片段
private async void button1_Click(object sender, RoutedEventArgs e)
{
await YoutubeAuth();
MessageBox.Show(token);
}
private async Task YoutubeAuth()
{
OAUth2Credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets { ClientId = YoutubeClientId, ClientSecret = YoutubeClientSecret },
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
token = OAUth2Credential.Token.TokenType;
}
代码
MessageBox.Show(token);
从未执行过。编辑:
我尝试过其他类似下面的简单代码,但MessageBox从未触发
private async void button1_Click(object sender, RoutedEventArgs e)
{
await YoutubeAuth();
MessageBox.Show(token);
}
private async Task YoutubeAuth()
{
token = "test token";
}
最佳答案
这似乎很有趣。我已经快速编写了WPF示例应用进行验证
MainWindow.xaml
<Window x:Class="TestAsyncTaskToYoutube.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestAsyncTaskToYoutube"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="button" Content="Button" />
</Grid>
</Window>
MainWindow.xaml.cs
using System.Threading.Tasks;
using System.Windows;
namespace TestAsyncTaskToYoutube
{
public partial class MainWindow : Window
{
private string token;
public MainWindow()
{
InitializeComponent();
button.Click += button_Click;
}
private async void button_Click(object sender, RoutedEventArgs e)
{
await YoutubeAuth();
MessageBox.Show(token);
}
private Task<int> YoutubeAuth()
{
token = "test token";
return Task.FromResult(0);
}
}
}
没问题MessageButton会按预期触发。我确信您的代码与我的代码在任何地方都有些不同:|
我们该怎样帮助你?
编辑:避免Task.FromResult()(.NET 4.5功能)
private async Task YoutubeAuth()
{
token = "test token";
}
关于c# - 将任务异步到YouTube,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29874634/