Revit开发之多线程


关于Revit开发其实是可以使用多线程的,但是是有限制的,目前发现只要在其他线程里启用Transaction,基本Revit就崩溃了,

但是在其他线程里不启用Transaction还是可以使用的,比如说我们要在Revit里检索一些东西,但这些东西又很多,需要的时间

比较长,这种情况我们就可以把检索的任务给其他线程,然后用户先可以先进行其他操作,

下面说一个简单的例子,在Task里检索建筑柱的数量,然后显示到Window里,但是检索数量的时候,用户可以在Window里进行

其他数据的输入:


namespace MultiThreading
{
    [Transaction(TransactionMode.Manual)]
    public class Class1:IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;
            ViewModel vm = new ViewModel(doc);
            if (vm.ShowWindow() ?? false)
            { 
                
            }
            return Result.Succeeded;
        }
    }


    public class ViewModel:ViewModelBase
    {
        public MainWindow win = null;
        public ViewModel(Document doc)
        {
            Task task = new Task(() =>
            {
                Thread.Sleep(10000);//由于检索太快,所以让Task等待10秒
                FilteredElementCollector temc = new FilteredElementCollector(doc);
                temc.OfCategory(BuiltInCategory.OST_Columns).OfClass(typeof(FamilyInstance));
                I = temc.Count();
                CanExecute = true;
            });
            task.Start();
            win = new MainWindow();
            win.DataContext = this;
        }


        private bool canExecute = false;
        public bool CanExecute
        {
            get
            {
                return canExecute;
            }
            set
            {
                canExecute = value;
                base.RaisePropertyChanged(() => CanExecute);
                base.RaisePropertyChanged(() => OK_Command);
            }
        }


        private int? i = null;
        public int? I
        {
            get
            {
                return i;
            }
            set
            {
                i = value;
                base.RaisePropertyChanged(() => I);
            }
        }
        public ICommand OK_Command
        {
            get
            {
                return new RelayCommand(() => {
                    win.DialogResult = true;
                    win.Close();
                },()=>CanExecute);
            }
        }
        public ICommand Cancel_Command
        {
            get
            {
                return new RelayCommand(() =>
                {
                    win.DialogResult = false;
                    win.Close();
                });
            }
        }
        public bool? ShowWindow()
        {
            return win.ShowDialog();
        }
    }
}


        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300">
   
       

你可能感兴趣的:(Revit开发随笔)