Click here to Skip to main content
15,922,533 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
static void Main(string[] args)
        {
            for(int i=0;i<50;i++)// without Parallel.for how can i achieve this
            {
                //var tsk = new Task(print, (object)i);
                //tsk.Start();

                var th = new Thread(print);
                th.Start((object)i);

                //Task.Factory.StartNew(print, (object)i);
            };
            Console.Read();
        }
        static void print(object threadcount)
        {
            Console.WriteLine(" {0} Start Time= {1}",threadcount           ,DateTime.Now.ToString());
            System.Threading.Thread.Sleep(4000);
            Console.WriteLine(" {0} end Time= {1}", threadcount, DateTime.Now.ToString());
        }


When i use threads the result is very fast where as when i use tasks the result is very slow

i want to run all at the same time this is acheived by using threads but not Tasks can any one correct my code so that we get the same result as threads


XML
sorry for that .. that is not the requirement..

class Program
    {
        static HttpListenerRequest _Req;
        static HttpListenerResponse _Resp;
        static HttpListener httpListener = null;
        static Thread th = null;
     //   static Task task1 = null;
        static bool m_ThreadStatus = true;

        static void Main(string[] args)
        {
            StartProcess("9001", "MYSERVER");
            Console.ReadLine();
        }



        /// <summary>
        /// To start the
        /// </summary>
        /// <param name="PortNumber"></param>
        /// <param name="VirtualDirectory"></param>
        /// <returns></returns>
        public static bool StartProcess(string PortNumber, string VirtualDirectory)
        {
            string Prefix = string.Format("http://*:{0}/{1}/", PortNumber, VirtualDirectory);
            try
            {
                Console.WriteLine("Listner started with :" +Prefix);
                httpListener = new HttpListener();
                httpListener.Prefixes.Add(Prefix);
                httpListener.Start();

                th = new Thread(startListner);
                th.Start();

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// Listner starts here
        /// </summary>
        public static void startListner()
        {
            while (m_ThreadStatus)
            {
                var tthred = new Thread(new ParameterizedThreadStart(AcceptClient));
                tthred.Start(httpListener.GetContext());
                //AcceptClient();
            }
            httpListener.Stop();
        }

        /// <summary>
        /// Client Process starts hrom here
        /// </summary>
        /// <param name="httpListenerContext"></param>
        private static void AcceptClient(object obj)
        {
            var httpListenerContext = (HttpListenerContext)obj;

            _Req = httpListenerContext.Request;
            _Resp = httpListenerContext.Response;

            using (StreamReader stre = new StreamReader(_Req.InputStream))
            {
               Console.WriteLine("Request: " + stre.ReadToEnd());
            }

            sendresponse("Got the Request");
        }

        private static void sendresponse(string strResponse)
        {
            try
            {
              //  Console.WriteLine("Response :" + strResponse);
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(_Resp.OutputStream))
                {
                    sw.Write(strResponse);
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (Exception ex)
            {

            }
        }
    }


Please check this function "startListner()" in that function insted of threads i want to use task

SQL
i have changed updated the "startListner()" the function with Task.factory because of unlimited requests like 1000 at a time are getting to this application in order to restrict this insted of parameterisedthread  i have update with TASK.Factory.Startnew() because of inbuilt thread POOl but this can able to handle only 30 tasks at a time ..





thank you
Posted
Updated 19-Aug-15 0:28am
v6

You did not even try, besides, your code makes little sense. I understand that you do it for some study, but it makes it unclear what should the task equivalent do. Right now, you are showing number of threads, but what do you want to show with tasks? This is a rhetorical question. You could still show, say, thread IDs or handles, to learn how threads are associated with tasks. You you could show numbers of tasks, but why?

So, I suggest you experiment with tasks all by yourself, only that it would be somewhat useful for you. You can start here:
https://msdn.microsoft.com/en-us/library/dd537609%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task%28v=vs.110%29.aspx[^],
https://code.msdn.microsoft.com/Samples-for-Parallel-b4b76364[^].

—SA
 
Share this answer
 
Comments
sagar.panuganti 19-Aug-15 6:25am    
thanks for the links... actually i am aware of TPL

i have changed updated the "startListner()" the function with Task.factory because of unlimited requests like 1000 at a time are getting to this application in order to restrict this insted of parameterisedthread i have update with TASK.Factory.Startnew() because of inbuilt thread POOl but this can able to handle only 30 tasks at a time .. what to do..
Sergey Alexandrovich Kryukov 19-Aug-15 9:10am    
I know you are aware of it, if you asked this question. Threading (more exactly, parallel execution) with a network listener is a right idea. You really need one task to listen to the new connections and another one to read from and write to network streams. I don't know why do you need so many tasks.

Now, parametrized thread is a bad idea, by the reason I explained in my answers about thread wrappers:
http://www.codeproject.com/Answers/646422/Making-Code-Thread-Safe#answer1,
http://www.codeproject.com/Answers/155852/How-to-pass-ref-parameter-to-the-thread#answer2,
http://www.codeproject.com/Answers/223412/change-paramters-of-thread-producer-after-it-start#answer1,
http://www.codeproject.com/Answers/485734/MultiThreadingplusinplusC-23#answer4.

—SA
Task is very fast. Task is advanced concept than the thread. you can use Task parallel library for lightning fast.

below I'm rewriting the same code but by using parallel tasks.

C#
static void Main(string[] args)
        {
            Parallel.For(0,50,(i) =>
            {
                Parallel.Invoke(()=>
                {
                   print((object)i);
                });
            };
            Console.Read();
        }
        static void print(object threadcount)
        {
            Console.WriteLine(" {0} Start Time= {1}",threadcount           ,DateTime.Now.ToString());
            System.Threading.Thread.Sleep(4000);
            Console.WriteLine(" {0} end Time= {1}", threadcount, DateTime.Now.ToString());
        }
 
Share this answer
 
Comments
sagar.panuganti 19-Aug-15 6:26am    
thanks ...

i have changed updated the "startListner()" the function with Task.factory because of unlimited requests like 1000 at a time are getting to this application in order to restrict this insted of parameterisedthread i have update with TASK.Factory.Startnew() because of inbuilt thread POOl but this can able to handle only 30 tasks at a time .. what to do..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900