抑制线程直到按下按钮为止

问题描述 投票:-1回答:1

我有一个正在使用MVVM创建的应用程序,我需要将工作拆分为一些线程,并且不知道如何以及为什么它无法正常工作。我需要UI保持响应状态,但是我想在单击按钮后第二次停用它。我的代码如下所示。最终的结果是,我从categoryconverter获得了收益,按钮又回到了isAvailable,线程被暂停,直到他们下次单击该按钮?但是现在它只是我无法工作的线程部分。

MainWindowViewModel:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Input;
using DataConverter.Checkers;
using DataConverter.Converters;
using DataConverter.Command;
using DataConverter.Objects;
using DataConverter.Threads; 

namespace DataConverter.ViewModels
{
    public class MainWindowViewModel : BaseViewModel
    {
       public List<Category> categories = new List<Category>();
       public string path { get; set; }

       public bool runButtonWorks { get; set; }
       public string errorMessage { get; set; }
       public ICommand run { get; set; }
       public MainWindowViewModel()
       {
            runButtonWorks = true;

            ThreadOne th = new ThreadOne(); 

            Thread t1 = new Thread(new ThreadStart(th.startProgram(path)));

            run = new RelayCommand(t1.Start);
       }
    }
}

ThreadOne:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataConverter.Checkers;
using DataConverter.Converters;

namespace DataConverter.Threads
{
    class ThreadOne
    {
        public void startProgram(string path)
        {

        }


        private bool CategoryWorker(string path)
        {
            FileCheck checkFile = new FileCheck();
            CategoryConverter categoryConverter = new CategoryConverter();

            if (checkFile.checkFile(path))
            {
                runButtonWorks = false;
                categoryConverter.getCategoryList(path);
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
c# multithreading mvvm
1个回答
1
投票

此行:

Thread t1 = new Thread(new ThreadStart(th.startProgram(path)));

startProgram(...)作为入口点创建线程。一旦启动线程,该方法中的代码就会在创建的线程中执行。由于该方法为空,因此它什么也不做。

然后存在通知UI线程工作线程已完成并接受其返回值的问题。有多种方法可以完成此操作,具体取决于您使用的UI平台。

[如果是我,我会看一下System.Threading.Tasks,它具有更简洁的API,尤其是当您想要从线程返回值时。

© www.soinside.com 2019 - 2024. All rights reserved.