i got a problem with running a async task with a thread that is called upon a button click and i dont know how to solve it.
When running it will stop directly after clicking the Upload button I already have tried several things, but nothing worked. One time it worked, but only till "VideosInsertRequest_ProgressChanged" but i dont remeber what i did xD Always getting the error that i cant access the object...
The code:
private void UploadVideo_Click(object sender, EventArgs e)
{
StatusLabel.Content = "Upload Video...";
Thread thead = new Thread(() =>
{
VideoUpload().Wait();
});
thead.IsBackground = true;
thead.Start();
}
private async Task VideoUpload()
{
UserCredential credential;
using (var stream = new FileStream("client_id.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// 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
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = VideoTitle.Text;
video.Snippet.Description = VideoDesc.Text;
string[] tags = Regex.Split(VideoTags.Text, ",");
video.Snippet.Tags = tags;
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = VideoPrivacy.Text; // or "private" or "public"
var filePath = VideoPath.Text; // Replace with path to actual movie file.
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += VideosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += VideosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
void VideosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
StatusLabel.Content = String.Format("{0} bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
StatusLabel.Content = String.Format("An error prevented the upload from completing.{0}", progress.Exception);
break;
}
}
void VideosInsertRequest_ResponseReceived(Video video)
{
StatusLabel.Content = string.Format("Video id '{0}' was successfully uploaded.", video.Id);
}