【发布时间】:2014-12-14 07:42:10
【问题描述】:
我正在开发一个项目,该项目提取 YouTube 视频的音频并将其保存到您的计算机上。 为此,我使用了来自 GitHub 的一个名为 YouTubeExtractor 的库。
我正在使用后台工作程序,以便在下载文件时使 UI 可用。这是我到目前为止的代码。
public partial class MainWindow : Window
{
private readonly BackgroundWorker worker = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
worker.DoWork += worker_DoWork;
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
}
private void downloadButton_Click(object sender, RoutedEventArgs e)
{
worker.RunWorkerAsync();
}
string link;
double percentage;
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
link = videoURL.Text;
}));
/*
* Get the available video formats.
* We'll work with them in the video and audio download examples.
*/
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);
/*
* We want the first extractable video with the highest audio quality.
*/
VideoInfo video = videoInfos
.Where(info => info.CanExtractAudio)
.OrderByDescending(info => info.AudioBitrate)
.First();
/*
* If the video has a decrypted signature, decipher it
*/
if (video.RequiresDecryption)
{
DownloadUrlResolver.DecryptDownloadUrl(video);
}
/*
* Create the audio downloader.
* The first argument is the video where the audio should be extracted from.
* The second argument is the path to save the audio file.
*/
var audioDownloader = new AudioDownloader(video, System.IO.Path.Combine("C:/Downloads", video.Title + video.AudioExtension));
// Register the progress events. We treat the download progress as 85% of the progress and the extraction progress only as 15% of the progress,
// because the download will take much longer than the audio extraction.
audioDownloader.DownloadProgressChanged += (send, args) => Console.WriteLine(args.ProgressPercentage * 0.85);
audioDownloader.AudioExtractionProgressChanged += (send, args) => Console.WriteLine(85 + args.ProgressPercentage * 0.15);
/*
* Execute the audio downloader.
* For GUI applications note, that this method runs synchronously.
*/
audioDownloader.Execute();
}
}
}
我的问题是我想显示这个
audioDownloader.DownloadProgressChanged += (send, args) => Console.WriteLine(args.ProgressPercentage * 0.85);
audioDownloader.AudioExtractionProgressChanged += (send, args) => Console.WriteLine(85 + args.ProgressPercentage * 0.15);
在标签或进度条等 UI 元素中,而不是在 Console.WriteLine 中
每当我这样做 label1.Text = (85 + args.ProgressPercentage * 0.15); 时,它都会给我一个类似
" 调用线程无法访问此对象,因为另一个线程拥有它。"
我知道你可以通过委托来解决这个问题,我需要一个明确的说明。
谢谢。
【问题讨论】:
-
你已经知道如何解决这个问题了。
this.Dispatcher.Invoke. -
@SLaks 是的,但是当我尝试用它来解决它时,它给了我更多的错误,我不知道我是在执行这个错误还是......但是,名为“链接”工作完美,因为我从 UI 获取文本,在 UI 上显示不起作用。
-
阅读错误,并向我们展示您的尝试。此外,使用 BackgroundWorker 并没有任何好处。
-
您应该使用任务 (msdn.microsoft.com/en-us/library/…),为什么不使用现有基础架构来报告进度 (msdn.microsoft.com/en-us/library/…)?
-
@SLaks 为什么你认为我不应该使用 BackgroundWorker?
标签: c# youtube download background-process