0

Take a look at the following script:

 await Task.Run(() =>
 {

                    //Importing data from OMDB
                    WebClient OMDB = new WebClient();
                    string ReqURL = "http://www.omdbapi.com/?t=the+revenant&apikey=***";
                    var RawData = OMDB.DownloadString(ReqURL);
                    var JsonData = JsonConvert.DeserializeObject<csOMDBData.Rootobject>(RawData);
                    var OMDBData = JsonData;
                    txtReport.text = "Done!";
});

I'm using this script for converting a raw data that I get by an API form OMDB to JSON. After converting, I need to change the text of a label called "txtReport" to "Done!" but I get the "Cross-thread operation in not valid!" error!

I have red all the related posts but couldn't find such a situation (Inside a task)! & because I'm new to Visual C# I don't even understand the solutions. If you can, please edit my script, I will learn by edited script. Thanks a lot...

2 Answers2

2
textReport.Invoke(new Action(() => textReport.Text = "Done!"));
koviroli
  • 1,422
  • 1
  • 15
  • 27
-1

// modified code is below, when the task has completed you need to be on the correct thread to update the main GUI thread

await Task.Run(() => {

                //Importing data from OMDB
                WebClient OMDB = new WebClient();
                string ReqURL = "http://www.omdbapi.com/?t=the+revenant&apikey=***";
                var RawData = OMDB.DownloadString(ReqURL);
                var JsonData = JsonConvert.DeserializeObject<csOMDBData.Rootobject>(RawData);
                var OMDBData = JsonData;

}); // to avoid the cross threading the followng line should be places after the // block of code above txtReport.text = "Done!";

Gbhairon
  • 1
  • 2
  • 1
    I needed to access txtReport inside Task not after completing... However @koviroli solved it! thanks –  May 30 '18 at 09:23