如何使用任务代替或使用线程 [英] How to use task instead or Threads

查看:55
本文介绍了如何使用任务代替或使用线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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());
        }





当我使用线程时,结果非常快,而当我使用任务时结果非常慢



i想要同时运行所有这些都是通过使用线程实现的但不是任务可以任何人纠正我的代码,以便我们得到与线程相同的结果







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


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)
            {

            }
        }
    }





请检查此功能startListner()在该功能中我想要使用的线程任务





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

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

推荐答案

你甚至没有尝试,此外,你的代码没什么意义。我知道你是为了一些研究而做的,但它不清楚这项任务应该做什么。现在,您显示的是线程数,但是您希望在任务中显示什么?这是一个修辞问题。您仍然可以显示线程ID或句柄,以了解线程如何与任务相关联。你可以展示一些任务,但为什么呢?



所以,我建议你自己试验一下任务,只是对你有用。你可以从这里开始:

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
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


任务非常快。任务是高级概念而不是线程。你可以使用任务并行库快速闪电。



以下我正在重写相同的代码,但使用并行任务。



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.

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());
        }


这篇关于如何使用任务代替或使用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆