private async void OnSearchButtonClick(object sender, RoutedEventArgs e)
{
string searchText = SearchTextBox.Text;
if (!string.IsNullOrEmpty(searchText))
{
FolderTreeView.IsEnabled = false; // Disable the UI while searching
// Start the timer and reset the elapsed time
_elapsedTime = TimeSpan.Zero;
_searchTimer.Start();
var result = await _folderSearchService.SearchTreeViewItem(FolderTreeView, searchText);
// Stop the timer once the search is finished
_searchTimer.Stop();
TimeCountLabel.Text = $"Search Time: {_elapsedTime:mm\\:ss}"; // Display final time
if (result != null)
{
result.IsSelected = true;
result.BringIntoView();
}
else
{
MessageBox.Show("Folder not found.", "Search Result", MessageBoxButton.OK, MessageBoxImage.Information);
}
FolderTreeView.IsEnabled = true; // Re-enable the UI after searching
}
}
Я запускаю таймер на этой строке
_searchTimer.Start();
перед началом поиска по этой строке
var result = await _folderSearchService.SearchTreeViewItem(FolderTreeView, searchText);
но я вижу, что поиск начинается до запуска таймера. таймер запускается примерно через 2-3 секунды после начала поиска.
Я пробовал использовать Dispatcher.Invoke(() =>, но это не сильно изменилось.
это версия с Dispatcher.Invoke
private async void OnSearchButtonClick(object sender, RoutedEventArgs e)
{
string searchText = SearchTextBox.Text;
if (!string.IsNullOrEmpty(searchText))
{
FolderTreeView.IsEnabled = false; // Disable the UI while searching
// Start the timer and reset the elapsed time
_elapsedTime = TimeSpan.Zero;
_searchTimer.Start();
// Force UI to update before continuing with the search
await Task.Run(() =>
{
Dispatcher.Invoke(() =>
{
// This forces the UI to update and start the timer before the search begins.
TimeCountLabel.Text = "Timer: 00:00";
});
});
// Begin searching
var result = await _folderSearchService.SearchTreeViewItem(FolderTreeView, searchText);
// Stop the timer once the search is finished
_searchTimer.Stop();
TimeCountLabel.Text = $"Timer: {_elapsedTime:mm\\:ss}"; // Display final time
if (result != null)
{
result.IsSelected = true;
result.BringIntoView();
}
else
{
MessageBox.Show("Folder not found.", "Search Result", MessageBoxButton.OK, MessageBoxImage.Information);
}
FolderTreeView.IsEnabled = true; // Re-enable the UI after searching
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... me-when-th