-1

i need to get threads running for my c# project

as i have a list of int that calling function

example

    protected void Page_Load(object sender, EventArgs e)
          {
            list<int> lst=new list<int>();

            lst.addrange(/// get list of int from data base);

            foreach(int number in lst)
            {
            call(number );
            }


getAllThreads();
            }


        public void call(int x)
        {
          Thread newThread = new Thread(() => { calc(x); });
          newThread.Start();
           newThread.name=x.tostring();
        }

        public void calc(int x)
        {
        ..... do something
        }

and i need to know which threads still running or finished

ie

i need to know which int still running or finished

i tried to use Thread.CurrentThread.Name

as in other function

private void getAllThreads()
        {
            string name= Thread.CurrentThread.Name;
        }

but it always null

i tried using

Thread.CurrentThread.ManagedThreadId

but it's value different than

 Thread.id
  • The easiest thing to do is move to `await`/`Task`. That or muck about with old school events –  Jun 10 '18 at 12:13
  • `Thread` is used for fire-and-forget threads where you do not expect any response from the thread. If you want to be alerted when the thread is done you should use `BackgroundWorker` of `async/await`. – Dour High Arch Jun 10 '18 at 20:18

1 Answers1

0

Try using a library suited for this kind of thing. Microsoft's Reactive Framework is perfect.

Here's the code:

protected void Page_Load(object sender, EventArgs e)
{
    List<int> lst = new List<int>(new[] { 1, 3, 3 });
    /// get list of int from data base);

    var query =
        from number in lst.ToObservable()
        from result in Observable.Start(() => calc(number))
        select result;

    query
        .Subscribe(
            result =>
            {
                /* can handle each result here */
            },
            () =>
            {
                /* all done here */
            });
}

This automagically manages all of the threads for you.

Just NuGet "System.Reactive" and add using System.Reactive.Linq; to your code.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172