线程抑制线程,直到按下按钮



我正在创建一个使用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;
}
}
}
}

此行:

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

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

然后是通知UI线程工作线程已完成并接受其返回值的问题。有不同的方法可以实现这一点,具体取决于您使用的UI平台。

如果我是你,我会看看System.Threading.Tasks,它有一个更干净的API,特别是当你想要从你的线程返回值时。

最新更新