0

What I want to achieve is create a global task which can be executive n times at one run but it can take an object as parameter and with different values, as it is shown next

I have a list with all objects that my global task is going to receive,

List<string> StringList = new List<string>();
StringList.Add("A");
StringList.Add("C");
StringList.Add("B");
StringList.Add("D");
StringList.Add("E");
StringList.Add("F");

Then I have a delegate function list

List<Func<string, string>> TasksList = new List<Func<string, string>>();

StringList.ForEach(c=> {
                TasksList.Add(x => Push(c));
            });

and then I want to call each task in this list to be executive, what I’m seeing it is that I have to set the parameter to be called, in this case i put "A" for all of them, but it takes the first initialization which is not bad, because it is I want.

var resultII = TasksList.Select(c => Observable.Start(() => c("A"))).CombineLatest().Finally(() => Console.WriteLine("Done!"));

OUTPUT: 

Executing C on Thread: 4 
Executing A on Thread: 5 
Executing B on Thread: 7 
Executing D on Thread: 7 
Executing E on Thread: 5 
Executing F on Thread: 4

Done! 
5 
4 
7 
7 
5 
4

But my question is, Is there any another way to do this? every time that I im calling Observable.Start these tasks were already ran? or they just start when I call them with Observable.Start? passing an "A" value without taking in account first initialization (StringList.Add("A") ,StringList.Add("C")...) is a bug or what’s happening?

  • You really should provide a [mcve]. The code you've provided cannot be run so it's a bit of a guess as to what it does. – Enigmativity Apr 18 '18 at 08:52

1 Answers1

1

It's a little vague what you're asking, but how does this look?

void Main()
{
    List<string> StringList = new List<string>()
    {
        "A", "B", "C", "D", "E", "F"
    };

    var query =
        StringList
            .ToObservable()
            .SelectMany(c => Observable.FromAsync(() => Push(c)))
            .ToArray();

    var result = query.Wait();

    Console.WriteLine(String.Join(", ", result));
}

public Task<string> Push(string input)
{
    return Task.Factory.StartNew(() =>
    {
        var id = System.Threading.Thread.CurrentThread.ManagedThreadId;
        Console.WriteLine($"Executing {input} on Thread: {id}");
        return input;
    });
}

That gives me:

Executing A on Thread: 19
Executing D on Thread: 22
Executing B on Thread: 18
Executing F on Thread: 22
Executing E on Thread: 19
Executing C on Thread: 16
A, D, B, F, E, C
Enigmativity
  • 113,464
  • 11
  • 89
  • 172