我目前正在为学校项目开发软件。在此软件中,我需要在YouTube上发布视频(使用YouTube数据API v3),并在此过程中显示进展情况。每次进度发生变化时,我都会调用一个事件,并在控制台中显示它。因为我的应用程序是一个winForm,我需要在progressBar(或类似的东西)中显示它。当我尝试这样做时,它给了我一个错误: “跨线程操作无效:控制'progressBar1'从其创建的线程以外的线程访问。” 我已经尝试过这样做了:
progressBar1.BeginInvoke(new MethodInvoker(delegate { progressBar1.Value = prog; }));
它没有给我一个错误,但它只显示最后的进展(当100%时),所以我需要一种方法在过程中显示。
以下是调用事件的代码:
UserCredential credential;
using (var stream = new FileStream("client_secrets.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 = title[i];
video.Snippet.Description = description[i];
string[] tags = tag[i].Split(',');
video.Snippet.Tags = tags;
video.Snippet.CategoryId = category[i]; // See https://gist.github.com/dgp/1b24bf2961521bd75d6c
video.Status = new VideoStatus();
video.Status.PrivacyStatus = privacy[i]; // or "private" or "public" or "unlisted"
var filePath = vidpath[i]; // Replace with path to actual movie file.
current_vid = i;
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
const int KB = 0x400;
var minimumChunkSize = 256 * KB;
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
// The default chunk size is 10MB, here will use 1MB.
videosInsertRequest.ChunkSize = minimumChunkSize * 4;
videosInsertRequest.Upload();
}
这是事件:
switch (progress.Status)
{
case UploadStatus.Uploading:
progressBar1.BeginInvoke(new MethodInvoker(delegate { progressBar1.Value = Convert.ToInt32(progress.BytesSent * 100 / total_size); }));
Console.WriteLine(progress.BytesSent * 100 / total_size);
break;
case UploadStatus.Failed:
Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
break;
}
答案 0 :(得分:0)
我能够纠正这个问题的唯一方法是创建一个控制台应用程序,并在我想要进展时显示控制台。
感谢您的支持。