C#WPF如何在单击按钮的线程上运行异步任务

时间:2018-11-17 01:01:11

标签: c# .net wpf multithreading upload

我遇到了一个运行异步任务的问题,该任务在单击按钮时被调用,我不知道如何解决它。

运行时,单击“上传”按钮后,它将立即停止 我已经尝试了几件事,但是没有任何效果。 它曾经工作过,但是直到“ VideosInsertRequest_ProgressChanged”才有效,但是我不记得我做了xD 总是收到我无法访问该对象的错误...

代码:

        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);
    }

2 个答案:

答案 0 :(得分:0)

您需要将ICommand与RelayCommandAsync一起使用,并将Button命令绑定到该icommand。 最好在wpf中使用MVVM创建一个viewmodel类

public class MoneyPageViewModel: INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        private ICommand _readAdminVersions;

        public ICommand readAdminVersions
        {
            get
            {
                return _readAdminVersions ??
                       (_readAdminVersions = new 
                        RelayCommandAsync(executeReadAdminVersions, (c) => true));
            }
        }
        private async Task executeReadAdminVersions()
        {//your code goes here
        }
    }  

如果您停留在INotifyPropertyChanged部分,只是在网络上看到简单的实现,则此代码是由ReSharper jetbrains自动生成的,或者vs 2017不知道:)
这是relayCommandAsync类:

public class RelayCommandAsync : ICommand
    {
        private readonly Func<Task> _execute;
        private readonly Predicate<object> _canExecute;
        private bool isExecuting;

        public RelayCommandAsync(Func<Task> execute) : this(execute, null) { }

        public RelayCommandAsync(Func<Task> execute, Predicate<object> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (!isExecuting && _canExecute == null) return true;
            return (!isExecuting && _canExecute(parameter));
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public async void Execute(object parameter)
        {
            isExecuting = true;
            try { await _execute(); }
            finally { isExecuting = false; }
        }
    }  

将视图模型添加到xaml:

        <Grid.Resources>
            <model:MoneyPageViewModel x:Key="MoneyPageViewModel"></model:MoneyPageViewModel>
        </Grid.Resources>

然后将按钮绑定到该命令:

<Button Command="{Binding readAdminVersions , Source={StaticResource MoneyPageViewModel}}>

答案 1 :(得分:0)

您似乎正在尝试访问其他线程上的UI元素。您可以使用调度程序在UI线程上执行该代码。试试这个:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="spinnerItemStyle">@style/spinnerText</item>
    <item name="spinnerDropDownItemStyle">@style/spinnerText</item>
</style>
<style name="spinnerText">
    <item name="textColor">#000000</item>
</style>