2013-04-23 105 views
2

我正在构建设备模拟器。当它启动时,它需要一些时间才能初始化。这将通过开启并立即进入“初始化”状态而在逻辑上表示,并且在一段时间后进入“就绪”状态。如何在不阻挡UI的情况下向WPF程序添加延迟

我正在使用MVVM,所以ViewModel现在将代表所有的设备逻辑。每个可能的状态都有一个数据查询样式,可以由View查看。如果我只是在构建视图模型时设置状态,视图将呈现正确的外观。

我想要做的是创建一个“超时状态”,即当发生某些事件(启动应用程序,单击某个按钮)时,设备进入一个固定时间的状态,然后回退到“就绪”或“空闲”状态。

我想过使用睡眠,但睡眠阻止用户界面(所以他们说)。所以我想使用线程,但我不知道如何去做。这是我这么远:

using System.ComponentModel; 

namespace EmuladorMiotool { 
    public class MiotoolViewModel : INotifyPropertyChanged { 
     Estados _estado; 

     public Estados Estado { 
      get { 
       return _estado; 
      } 
      set { 
       _estado = value; 
       switch (_estado) { 
        case Estados.WirelessProcurando: 
         // WAIT FOR TWO SECONDS WITHOUT BLOCKING GUI 
         // It should look like the device is actually doing something 
         // (but not indeed, for now) 
         _estado = Estados.WirelessConectado; 
         break; 
       } 
       RaisePropertyChanged("Estado"); 
      } 
     } 

     public MiotoolViewModel() { 
      // The constructor sets the initial state to "Searching" 
      Estado = Estados.WirelessProcurando; 
     } 

     public event PropertyChangedEventHandler PropertyChanged; 
     protected virtual void RaisePropertyChanged(string propertyName) { 
      PropertyChangedEventHandler handler = PropertyChanged; 
      if (handler != null) 
       handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 

    } 

    public enum Estados { 
     UsbOcioso, 
     UsbAquisitando, 
     UsbTransferindo, 
     WirelessNãoPareado, 
     WirelessPareado, 
     WirelessDesconectado, 
     WirelessProcurando, 
     WirelessConectado, 
     WirelessAquisitando, 
     DataLoggerOcioso, 
     DataLoggerAquisitando, 
     Erro, 
     Formatando 
    } 
} 

回答

1

首先具有一个属性(的getter/setter)睡眠/异步操作被认为是不好的做法

尝试以此为睡眠的替代品,而不会阻塞UI线程:

创建一个函数来设置EstadoEstados.WirelessProcurando

假设WirelessProcurando意味着正开始和WirelessConectado手段初始化

.net45

private async Task SetWirelessProcurando(int milliSeconds) { 
    Estado = Estados.WirelessProcurando; 
    await Task.Delay(milliSeconds); 
    Estado = Estados.WirelessConectado; 
} 

我们有函数返回一个Task VS void的原因仅仅是让打电话的人是否需要await这个功能如果逻辑相应

如果需要它你不能使用await

private void SetWirelessProcurando(int milliSeconds) { 
    Estado = Estados.WirelessProcurando; 
    var tempTask = new Task 
    (
    () => { 
     Thread.Sleep(milliSeconds); 
     System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => Estado = Estados.WirelessConectado)); 
    }, 
    System.Threading.Tasks.TaskCreationOptions.LongRunning 
    ); 
    tempTask.Start(); 
} 

现在每当你想改变setter时调用这个函数将会立即将状态设置为“Intiialising”并且在给定的milliSeconds切换到Initialised状态之后。

+0

我与.NET 4.0在这里,所以我认为'async'不可用,是不是? – heltonbiker 2013-04-23 19:18:32

+0

@heltonbiker它不在.net4 :(你可以使用我刚刚添加的替代方法,它应该可以正常工作.net4 – Viv 2013-04-23 19:19:39

+0

此外,如果我尝试在初始化过程运行时“获取”设备状态,返回'Estados.WirelessProcurando' – heltonbiker 2013-04-23 19:20:18

相关问题