Translate all Dispatcher().RunAsync([](){}) lambdas into coroutines #5514

Open
opened 2026-01-31 00:15:13 +00:00 by claunia · 0 comments
Owner

Originally created by @DHowett-MSFT on GitHub (Dec 11, 2019).

I believe there is a trivial mechanical translation that'll get us better code clarity and perhaps a better understanding of the flow of ownership through our code.

from

void TerminalPage::_SetFocusedTabIndex(int tabIndex)
{
    auto tab = _tabs.at(tabIndex);
    auto weakThis{ get_weak() };
    _tabView.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [tab, weakThis]() {
        if (auto page{ weakThis.get() })
        {
            page->_tabView.SelectedItem(tab->GetTabViewItem());
        }
    });
}

to

winrt::fire_and_forget TerminalPage::_SetFocusedTabIndex(int tabIndex)
{
    // GH#1117: This is a workaround because _tabView.SelectedIndex(tabIndex)
    //          sometimes set focus to an incorrect tab after removing some tabs
    auto tab = _tabs.at(tabIndex);
    auto weakThis{ get_weak() };

    co_await winrt::resume_foreground(_tabView.Dispatcher()); // transition to the dispatcher thread

    if (auto page{ weakThis.get() })
    {
        page->_tabView.SelectedItem(tab->GetTabViewItem());
    }
}

There's a bunch more information about concurrency and coroutines in C++/WinRT here.

Originally created by @DHowett-MSFT on GitHub (Dec 11, 2019). I believe there is a trivial mechanical translation that'll get us better code clarity and perhaps a better understanding of the flow of ownership through our code. ### from ```c++ void TerminalPage::_SetFocusedTabIndex(int tabIndex) { auto tab = _tabs.at(tabIndex); auto weakThis{ get_weak() }; _tabView.Dispatcher().RunAsync(CoreDispatcherPriority::Normal, [tab, weakThis]() { if (auto page{ weakThis.get() }) { page->_tabView.SelectedItem(tab->GetTabViewItem()); } }); } ``` ### to ```c++ winrt::fire_and_forget TerminalPage::_SetFocusedTabIndex(int tabIndex) { // GH#1117: This is a workaround because _tabView.SelectedIndex(tabIndex) // sometimes set focus to an incorrect tab after removing some tabs auto tab = _tabs.at(tabIndex); auto weakThis{ get_weak() }; co_await winrt::resume_foreground(_tabView.Dispatcher()); // transition to the dispatcher thread if (auto page{ weakThis.get() }) { page->_tabView.SelectedItem(tab->GetTabViewItem()); } } ``` There's a bunch more information about concurrency and coroutines in C++/WinRT [here](https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/concurrency-2).
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/terminal#5514