0
Dictionary<string, int> myDictionary = new Dictionary<string, int>();

is created inside background event _DoWork and returned like so:

e.Result = myDictionary;

now inside my _RunWorkerCompleted event I want to loop though result like so:

foreach (KeyValuePair<string, int> kvp in e.Result)
{
 ...
}

but I keep getting

Error CS1579 foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public instance or extension definition for 'GetEnumerator'

Why is that? I can loop it inside DoWork event but not when I pass it to RunWorkerCompleted

Matic-C
  • 783
  • 2
  • 11
  • 16
  • Why are you using the obsolete BackgroundWorker class? Everything it does is actually easier to do with `Task.Run`, `async/await` and `IProgress`. On the other hand, simple things like making two consecutive async calls are extremely complicated to do with BGW – Panagiotis Kanavos Oct 18 '21 at 16:50
  • 1
    Can you provide a minimally reproducible example? – emagers Oct 18 '21 at 16:51
  • 3
    Because `Result` is of type `object`, you need to cast it to `Dictionary` `foreach (KeyValuePair kvp in (Dictionary) e.Result)` – Evk Oct 18 '21 at 16:53
  • @Evk thank you for the explanation that fixes it. – Matic-C Oct 18 '21 at 17:02
  • @Panagiotis Kanavos well it works I spent a lot of time on it and I didn't know I could make separate thread in an easier way – Matic-C Oct 18 '21 at 17:02
  • @Orangutan if it worked well you wouldn't have to deal with `object` and get the compilation error you got. You need to cast the result but that's not obvious. On the other hand, `KeyValuePair result=await Task.Run(()=>myFunction()); foreach(KeyValuePair kvp in result){...}` simply works – Panagiotis Kanavos Oct 18 '21 at 17:06
  • 1
    @Orangutan you can find [here](https://stackoverflow.com/questions/12414601/async-await-vs-backgroundworker/64620920#64620920) an example of how to replace a `BackgroundWorker` with `Task.Run` & async/await. – Theodor Zoulias Oct 18 '21 at 17:06
  • @Orangutan casting from object may not seem so bad when dealing with classes. With value types like structs, integers, etc casting *wraps* them in an `object` that needs to be garbage collected. – Panagiotis Kanavos Oct 18 '21 at 17:07

0 Answers0