Fixus
Fixus

Reputation: 4641

How to get UI elements in diffrent Thread?

In my app I'm saving data to my database (SQLite). I don't want to block my UI so I save the data in diffrent task

            await Task.Run(() => this.SaveTracks(books, filesCollection));

I get TextBox from my dictionary with data

TextBox tmpTextBox = parseData["title_" + i] as TextBox;

When it wasn't in diffrent Task it works great but when I've set in with Task.Run I get Exception that I can't use it cause I invoke element in diffrent thread. How can I not block my UI by doing it in diffrent Task and get data from UI elements in main Thread

Upvotes: 0

Views: 251

Answers (2)

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47068

Get the TextBox.Text value before you start the Task and pass that value as an argument.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503280

Two options:

  • Split up the bigger operation so that your loop (I assume there's a loop) still executes in the UI thread, but each individual save operation is a separate task in the background
  • Fetch all the UI information you need before you create the task, and capture that information so the task never needs to access the UI

Either way the result is the same: you only access the UI elements in the UI thread.

Upvotes: 3

Related Questions