2

How can i pass for example the text of a textBox UI element into a Task.Run() method? This code will throw an exception(... other thread owns it). When i pass the filter variabele, the exception is gone, is this because the string gets passed as value?

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));
    }
}
svick
  • 236,525
  • 50
  • 385
  • 514
pic-o-matic
  • 241
  • 1
  • 3
  • 12
  • 2
    Yes, thats the case – Sir Rufo Jun 27 '17 at 19:09
  • 2
    basically, yes :-) read more on it [here](https://stackoverflow.com/a/30120785/1132334). But the opposite is not true: it fails with the textbox because the textbox is a [control on the UI thread](https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls), not because its passed by ref vs. by val. – Cee McSharpface Jun 27 '17 at 19:10

1 Answers1

3

You can't use objects with thread affinity (such as the TextBox object) in a thread other than the one that owns that object.

But most objects don't have thread affinity. They are not owned by any particular thread and can be used anywhere. That includes the string object returned by filterTextBox.Text, which you store in the filter local variable.

So, just use that value instead:

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

Note that you should not need to specify the type parameter for the Task.Run() method call either. The compiler will infer the type based on the expression used in the call.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136