0

При загрузке приложения заполняю TableAdapter. При его заполнении происходит подключение к серверу MS SQL. Если подключение отсутствует, то окно "зависает". Как запустить подключение в фоне.

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                monitorDataSet = ((BidsMonitor.MonitorDataSet)(this.FindResource("monitorDataSet")));
                // Загрузить данные в таблицу BidsView. Можно изменить этот код как требуется.
                bidsTA = new BidsMonitor.MonitorDataSetTableAdapters.BidsViewTableAdapter();
                System.Windows.Data.CollectionViewSource bidsVS = ((System.Windows.Data.CollectionViewSource)(this.FindResource("bidsViewViewSource")));

                this.statusIndicator.Fill = Brushes.Yellow;
                this.statusText.Text = "Подключение ...";
                this.statusText.Dispatcher.Invoke(new Action(() => {
                    try
                    {
                        // В следующей строке происходт подключение к серверу и считываение данных
                        bidsTA.Fill(monitorDataSet.BidsView);

                        bidsVS.View.MoveCurrentToFirst();
                        this.statusIndicator.Fill = Brushes.Green;
                        this.statusText.Text = "Подключено";
                        this.updateTimeTextbox.Text = string.Format("Обновлено: {0}", DateTime.Now.ToString());
                    }
                    catch
                    {
                        this.statusIndicator.Fill = Brushes.Red;
                        this.statusText.Text = "отсутствует";
                    }
                }), DispatcherPriority.Background);                

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

1 ответ 1

3

Поручим это отдельной задаче Task.Run(), а вывод статуса Dispatcher.Invoke

Task.Run(() =>
{
    try
    {
        // В следующей строке происходт подключение к серверу и считываение данных
        bidsTA.Fill(monitorDataSet.BidsView);

        bidsVS.View.MoveCurrentToFirst();
        this.Dispatcher.Invoke(() => {
        this.statusIndicator.Fill = Brushes.Green;
        this.statusText.Text = "Подключено";
        this.updateTimeTextbox.Text = string.Format("Обновлено: {0}", DateTime.Now.ToString());
        });
    }
    catch
    {
      this.Dispatcher.Invoke(() => {
        this.statusIndicator.Fill = Brushes.Red;
        this.statusText.Text = "отсутствует";
       });
    }
});

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.