Basic _ C # thread processing

Source: Internet
Author: User
C # thread processing

Content

  • Use thread processing

  • How to: create and terminate a thread

  • How to: Use a thread pool

  • How to: Synchronize producer threads and user threads

 

Use thread pool

Use the threadpool class

The following example uses the. NET Framework thread pool to calculate the ten numbers between 20 and 40.FibonacciResult. EachFibonacciResults areFibonacciClass, which providesThreadPoolCallback. An object that represents the value of each Fibonacci will be created,ThreadPoolCallbackThe method is passed to queueuserworkitem, which allocates an available thread in the pool to execute this method.

Because for eachFibonacciAll objects provide a half-random value for calculation, and ten threads compete for the processor time. Therefore, it is impossible to know the time required to calculate all ten results in advance. Therefore, eachFibonacciAn instance that passes the manualresetevent class. When the calculation is complete, each object notifies the provided event object, so that the main thread uses waitall to stop execution until 10FibonacciAll objects are computed. ThenMainEachFibonacciResult.

using System;using System.Threading;public class Fibonacci{    public Fibonacci(int n, ManualResetEvent doneEvent)    {        _n = n;        _doneEvent = doneEvent;    }    // Wrapper method for use with thread pool.    public void ThreadPoolCallback(Object threadContext)    {        int threadIndex = (int)threadContext;        Console.WriteLine("thread {0} started...", threadIndex);        _fibOfN = Calculate(_n);        Console.WriteLine("thread {0} result calculated...", threadIndex);        _doneEvent.Set();    }    // Recursive method that calculates the Nth Fibonacci number.    public int Calculate(int n)    {        if (n <= 1)        {            return n;        }        return Calculate(n - 1) + Calculate(n - 2);    }    public int N { get { return _n; } }    private int _n;    public int FibOfN { get { return _fibOfN; } }    private int _fibOfN;    private ManualResetEvent _doneEvent;}public class ThreadPoolExample{    static void Main()    {        const int FibonacciCalculations = 10;        // One event is used for each Fibonacci object        ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];        Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];        Random r = new Random();        // Configure and launch threads using ThreadPool:        Console.WriteLine("launching {0} tasks...", FibonacciCalculations);        for (int i = 0; i < FibonacciCalculations; i++)        {            doneEvents[i] = new ManualResetEvent(false);            Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);            fibArray[i] = f;            ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);        }        // Wait for all threads in pool to calculation...        WaitHandle.WaitAll(doneEvents);        Console.WriteLine("All calculations are complete.");        // Display the results...        for (int i = 0; i < FibonacciCalculations; i++)        {            Fibonacci f = fibArray[i];            Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);        }    }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.