1

我正在尝试将我服务器上的视频直接上传到 YouTube。当用户添加视频时,它会被复制到 YouTube。

添加视频的用户操作应该开始上传过程,这可能需要一段时间。表单,即使是异步表单,也不应该坐在那里等待这种情况发生。它应该刚刚开始并允许用户继续前进,相信它正在后台得到照顾。

为此,我尝试使用 system.threading.backgroundworker。我希望这个过程会开始,网络应用程序会继续前进。它不是。无论是异步回发还是完整回发,它都处于挂起状态,并等待上传完成,然后再返回和更新 lblmsg.text。

我应该采取不同的方式来解决这个问题,以便用户可以启动上传过程而不是等待它完成?到目前为止,这是我的代码:

Sub up_load(s As Object, e As EventArgs)
    Dim worker As BackgroundWorker = New BackgroundWorker

    worker.WorkerReportsProgress = True
    worker.WorkerSupportsCancellation = True
    AddHandler (worker.DoWork), AddressOf begin_upload

    'call this and move on?
    worker.RunWorkerAsync()

    lblmsg.Text = "Successfully initiated upload"

End Sub

Sub begin_upload(s As Object, e As DoWorkEventArgs)

    Dim request As New YouTubeRequest(settings)
    Dim vidupload As New Video()

    vidupload.Title = "My Big Test Movie"
    vidupload.Tags.Add(New MediaCategory("Nonprofit", YouTubeNameTable.CategorySchema))
    vidupload.Keywords = "church, jesus"
    vidupload.Description = "See the entire video"
    vidupload.YouTubeEntry.Private = False
    vidupload.YouTubeEntry.setYouTubeExtension("location", "Downers Grove, IL")
    vidupload.YouTubeEntry.MediaSource = New MediaFileSource("c:\users\greg\test3.asf", "video/x-ms-wmv")

    Dim createdVideo As Video = Request.Upload(vidupload)
End Sub
4

1 回答 1

0

您可能需要查看Task Parallel Library以将多线程添加到您的代码中。鉴于您提供的代码:

添加此导入语句

Imports System.Threading.Tasks

并用这个简单的语句替换所有后台工作逻辑:

    Dim uploadTask As Task = Task.Factory.StartNew(Sub()
                                                       Dim request As New YouTubeRequest(settings)
                                                       Dim vidupload As New Video()

                                                       vidupload.Title = "My Big Test Movie"
                                                       vidupload.Tags.Add(New MediaCategory("Nonprofit", YouTubeNameTable.CategorySchema))
                                                       vidupload.Keywords = "church, jesus"
                                                       vidupload.Description = "See the entire video"
                                                       vidupload.YouTubeEntry.Private = False
                                                       vidupload.YouTubeEntry.setYouTubeExtension("location", "Downers Grove, IL")
                                                       vidupload.YouTubeEntry.MediaSource = New MediaFileSource("c:\users\greg\test3.asf", "video/x-ms-wmv")

                                                       Dim createdVideo As Video = request.Upload(vidupload)
                                                   End Sub)

现在你有uploadTask在后台上传你的视频,你的UI线程将可以自由地处理其他代码。如果您想要取消和进度报告,它确实会变得有点复杂,但顶部的链接应该可以帮助您入门。

于 2012-04-28T02:12:58.223 回答