user266003
user266003

Reputation:

Class Task in C# and the different results

There's a code that reads a file and makes some calculating operations with its content in another thread using the classes Task and StreamReader.

 Task t= new Task(() => DoSomeWork(myFile));
 t.Start();

But inspite of the file is immutable sometimes I'm getting the different results! Why? What should I do to resolve it?

Upvotes: 0

Views: 234

Answers (2)

Drew Marsh
Drew Marsh

Reputation: 33379

One problem I can see off the bat is, if there are multiple word matches, the first time you come across each new word you are recreating the entire GridView. I would recommend creating the GridView before entering the loop to process words... if not just have the GridView be static in the ListView's definition at design time.

That said, this is more of a performance issue (constantly resetting the view) than an issue with the data. If you can post your FileWordInfo view model class implementation it might unveil some other problems.

Upvotes: 0

tmesser
tmesser

Reputation: 7666

You've clearly got something inside DoSomeWork() that is not thread safe. The most likely candidate for this is some static code, since that would mean that there's only one copy of that particular piece of code in memory. One instance of DoSomeWork() could get context switched out, and another instance would then pick up on the state of the static method, giving you some unpredictable results.

Other things could include improper use of dependency injection, a singleton object that's being shared, certain libraries being improperly used as asynchronous, or a couple other things - this is what Drew was talking about when he asked for more information.

Upvotes: 1

Related Questions