并发多线程C#

时间:2016-03-09 06:53:12

标签: c# wpf multithreading

我正在处理带有telerik控件的WPF应用程序。

我使用绑定到集合的RadListBox。当我选择每个RadListBoxItem时,BindedItem的详细视图将显示在附近的面板中。一次只能选择一个RadListBoxItem

在下面的逻辑中,我提供了以下功能,

  1. 修改
  2. 切换到新
  3. 保存或放弃警报
  4. 保存/放弃
  5. 加载选定的
  6. 现在问题是当为Save / Discard抛出警报时,如果我单击save,则启动保存过程但在保存完成之前,加载也在另一个线程中运行。我必须检查保存是否完成并开始加载过程。

    // XAML代码:

    <telerik:RadListBox x:Name="lstMarketSeries" ItemsSource="{Binding SCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True, ValidatesOnDataErrors=True}" SelectedItem="{Binding SelectedMSeries, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" telerik:StyleManager.Theme="Windows8"> 
    <i:Interaction.Triggers>
       <i:EventTrigger EventName="SelectionChanged">
         <i:InvokeCommandAction Command="{Binding LoadSelected}"/>
       </i:EventTrigger>
    </i:Interaction.Triggers>
    </telerik:RadListBox> 
    

    //视图模型:

    public ICommand LoadSelected { get { return new RelayCommand(LoadSelectedSDetails); } }
    
    /// <summary>
    /// Load selected series
    /// </summary>
    private async void LoadSelectedSDetails()
    {
       if (SCollection != null)
       {
           if (!IsChanged())
           {
               bw = new BackgroundWorker();
               bw.RunWorkerAsync();
    
               bw.DoWork += (s, e) =>
               {
                    //Loading functionality here( Have to check if the save is complete)
               };
    
               bw.RunWorkerCompleted += (s, e) =>
               {
                    IsBusy = false;
               };
           }
           else
           { 
               await PutTaskDelay();  // This delay is to wait for save to complete
               LoadSelectedSDetails();
           }
    
    /// <summary>
    /// Check if collection is changed
    /// </summary>
    private bool IsChanged()
    {
        bool IsChanged = false;
        if (SCollection != null)
           IsChanged = SCollection.Where(x => x.IsChanged || x.IsNew).Count() > 0;
    
        if (IsChanged)
        {
           if (ShowMessages.SaveOrDiscardBox())
           {
              SaveAllDetails(); // Saving runs in a separate thread.
           }
           else
           {
              //Discard functionality goes here
           }
        }
    
        return IsChanged;
    }
    

    请帮助解决这个问题。

1 个答案:

答案 0 :(得分:0)

如果您想在Task执行后执行某些操作,可以使用ContinueWith

       var saveTask = new Task<ReturnedObject>(() =>  //if you don't need values in order to update the UI you can use Task not Task<T>
                    {
                      //do your save action and return something if you want 
                    });

                    //start thread
                    saveTask.Start();

                    saveTask.ContinueWith(previousTask =>
                    {//after the first thread is completed, this point will be hit

                        //loading action here

                        //UI region if needed
                            Application.Current.Dispatcher.BeginInvoke((ThreadStart)delegate
                            {
                              //update UI
                            }, DispatcherPriority.Render);               

                    }, TaskScheduler

    .FromCurrentSynchronizationContext());