Task.Run() 如何传递其他线程拥有的对象?

Task.Run() how to pass object owned by other thread?

我如何将文本框 UI 元素的文本传递给 Task.Run() 方法?此代码将抛出异常(...其他线程拥有它)。当我通过过滤器变量时,异常消失了,这是因为字符串作为值传递了吗?

private async void filterTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    if (currentSession.SessionFilenames != null)
    {
        string filter = filterTextBox.Text;
        dirListing.ItemsSource = await Task<IEnumerable<string>>.Run(()=> Filterfiles(filterTextBox.Text));
    }
}

您不能在拥有该对象的线程以外的线程中使用具有线程亲和性的对象(例如 TextBox 对象)。

但大多数对象具有线程关联。它们不属于任何特定线程,可以在任何地方使用。这包括 filterTextBox.Text 返回的 string 对象,您将其存储在 filter 局部变量中。

因此,只需使用该值即可:

dirListing.ItemsSource = await Task.Run(()=> Filterfiles(filter));

请注意,您也不需要为 Task.Run() 方法调用指定类型参数。编译器将根据调用中使用的表达式推断类型。