달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2016. 11. 24. 02:29

helpful classes 프로그래밍/C#2016. 11. 24. 02:29


  1. Dispatcher Class
  2. Thread Class
  3. ThreadPool Class
  4. WebClient Class
  5. GC Class




Dispatcher Class


https://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher(v=vs.110).aspx


Provides services for managing the queue of work items for a thread.

Namespace:   System.Windows.Threading
Assembly:  WindowsBase (in WindowsBase.dll)

Inheritance Hierarchy

System.Object
  System.Windows.Threading.Dispatcher


Remarks

The Dispatcher maintains a prioritized queue of work items for a specific thread.

When a Dispatcher is created on a thread, it becomes the only Dispatcher that can be associated with the thread, even if the Dispatcher is shut down.

If you attempt to get the CurrentDispatcher for the current thread and a Dispatcher is not associated with the thread, a Dispatcher will be created. A Dispatcher is also created when you create a DispatcherObject. If you create a Dispatcher on a background thread, be sure to shut down the dispatcher before exiting the thread.

If a Dispatcher is shut down, it cannot be restarted.

In WPF, a DispatcherObject can only be accessed by the Dispatcher it is associated with.  For example, a background thread cannot update the contents of a Button that is associated with the Dispatcher on the UI thread. In order for the background thread to access the Content property of the Button, the background thread must delegate the work to the Dispatcher associated with the UI thread. This is accomplished by using either Invoke or BeginInvokeInvoke is synchronous and BeginInvoke is asynchronous. The operation is added to the queue of the Dispatcher at the specified DispatcherPriority.

If BeginInvoke is called on a Dispatcher that has shut down, the status property of the returned DispatcherOperation is set to Aborted.

All of the methods on Dispatcher, with the exception of DisableProcessing, are free-threaded.

Objects that derive from DispatcherObject have thread affinity.

Objects that derive from Freezable are free-threaded when they are frozen. For more information, see Freezable Objects Overview.

Examples

The following example shows how to place an operation onto a Dispatcher. For the full source code of this example, see Single-Threaded Application with Long-Running Calculation Sample.

First, a delegate is created that accepts no arguments.

public delegate void NextPrimeDelegate();

Next, BeginInvoke(DispatcherPriority, Delegate) is called. This call to BeginInvoke(DispatcherPriority, Delegate) takes two parameters: the priority, which is set to DispatcherPriority.Normal, and the callback, which is passed in through an instance of the delegate NextPrimeDelegate.

startStopButton.Dispatcher.BeginInvoke(
    DispatcherPriority.Normal,
    new NextPrimeDelegate(CheckNextNumber));






Thread Class


https://msdn.microsoft.com/en-us/library/system.threading.thread(v=vs.110).aspx


Creates and controls a thread, sets its priority, and gets its status.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)


Remarks

When a process starts, the common language runtime automatically creates a single foreground thread to execute application code. Along with this main foreground thread, a process can create one or more threads to execute a portion of the program code associated with the process. These threads can execute either in the foreground or in the background. In addition, you can use the ThreadPool class to execute code on worker threads that are managed by the common language runtime.

In this section

Starting a thread
Retrieving Thread objects
Foreground and background threads
Culture and threads
Getting information about and controlling threads
Accessing the source code for the Thread class

Starting a thread

You start a thread by supplying a delegate that represents the method the thread is to execute in its class constructor. You then call the Startmethod to begin execution.

The Thread constructors can take either of two delegate types, depending on whether you can pass an argument to the method to be executed:

  • If the method has no arguments, you pass a ThreadStart delegate to the constructor. It has the signature:

    public delegate void ThreadStart()
    

    The following example creates and starts a thread that executes the ExecuteInForeground method. The method displays information about some thread properties, then executes a loop in which it pauses for half a second and displays the elapsed number of seconds. When the thread has executed for at least five seconds, the loop ends and the thread terminates execution.

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    public class Example
    {
       public static void Main()
       {
          var th = new Thread(ExecuteInForeground);
          th.Start();
          Thread.Sleep(1000);
          Console.WriteLine("Main thread ({0}) exiting...", 
                            Thread.CurrentThread.ManagedThreadId); 
       }
    
       private static void ExecuteInForeground()
       {
          DateTime start = DateTime.Now;
          var sw = Stopwatch.StartNew();
          Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority);
          do { 
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000.0);
             Thread.Sleep(500);
          } while (sw.ElapsedMilliseconds <= 5000);
          sw.Stop(); 
       }
    }
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.51 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.02 seconds
    //       Thread 3: Elapsed 1.53 seconds
    //       Thread 3: Elapsed 2.05 seconds
    //       Thread 3: Elapsed 2.55 seconds
    //       Thread 3: Elapsed 3.07 seconds
    //       Thread 3: Elapsed 3.57 seconds
    //       Thread 3: Elapsed 4.07 seconds
    //       Thread 3: Elapsed 4.58 seconds
    
  • If the method has an argument, you pass a ParameterizedThreadStart delegate to the constructor. It has the signature:

    public delegate void ParameterizedThreadStart(object obj)
    

    The method executed by the delegate can then cast (in C#) or convert (in Visual Basic) the parameter to the appropriate type.

    The following example is identical to the previous one, except that it calls the Thread(ParameterizedThreadStart) constructor. This version of the ExecuteInForeground method has a single parameter that represents the approximate number of milliseconds the loop is to execute.

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    public class Example
    {
       public static void Main()
       {
          var th = new Thread(ExecuteInForeground);
          th.Start(4500);
          Thread.Sleep(1000);
          Console.WriteLine("Main thread ({0}) exiting...", 
                            Thread.CurrentThread.ManagedThreadId); 
       }
    
       private static void ExecuteInForeground(Object obj)
       {
          int interval;
          try {
             interval = (int) obj;
          }
          catch (InvalidCastException) {
             interval = 5000;
          }
          DateTime start = DateTime.Now;
          var sw = Stopwatch.StartNew();
          Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                            Thread.CurrentThread.ManagedThreadId,
                            Thread.CurrentThread.ThreadState,
                            Thread.CurrentThread.Priority);
          do { 
             Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                               Thread.CurrentThread.ManagedThreadId,
                               sw.ElapsedMilliseconds / 1000.0);
             Thread.Sleep(500);
          } while (sw.ElapsedMilliseconds <= interval);
          sw.Stop(); 
       }
    }
    // The example displays output like the following:
    //       Thread 3: Running, Priority Normal
    //       Thread 3: Elapsed 0.00 seconds
    //       Thread 3: Elapsed 0.52 seconds
    //       Main thread (1) exiting...
    //       Thread 3: Elapsed 1.03 seconds
    //       Thread 3: Elapsed 1.55 seconds
    //       Thread 3: Elapsed 2.06 seconds
    //       Thread 3: Elapsed 2.58 seconds
    //       Thread 3: Elapsed 3.09 seconds
    //       Thread 3: Elapsed 3.61 seconds
    //       Thread 3: Elapsed 4.12 seconds
    

It is not necessary to retain a reference to a Thread object once you have started the thread. The thread continues to execute until the thread procedure is complete.

Retrieving Thread objects

You can use the static (Shared in Visual Basic) CurrentThread property to retrieve a reference to the currently executing thread from the code that the thread is executing. The following example uses the CurrentThread property to display information about the main application thread, another foreground thread, a background thread, and a thread pool thread.

using System;
using System.Threading;

public class Example
{
   static Object obj = new Object();

   public static void Main()
   {
      ThreadPool.QueueUserWorkItem(ShowThreadInformation);
      var th1 = new Thread(ShowThreadInformation);
      th1.Start();
      var th2 = new Thread(ShowThreadInformation);
      th2.IsBackground = true;
      th2.Start();
      Thread.Sleep(500);
      ShowThreadInformation(null); 
   }

   private static void ShowThreadInformation(Object state)
   {
      lock (obj) {
         var th  = Thread.CurrentThread;
         Console.WriteLine("Managed thread #{0}: ", th.ManagedThreadId);
         Console.WriteLine("   Background thread: {0}", th.IsBackground);
         Console.WriteLine("   Thread pool thread: {0}", th.IsThreadPoolThread);
         Console.WriteLine("   Priority: {0}", th.Priority);
         Console.WriteLine("   Culture: {0}", th.CurrentCulture.Name);
         Console.WriteLine("   UI culture: {0}", th.CurrentUICulture.Name);
         Console.WriteLine();
      }   
   }
}
// The example displays output like the following:
//       Managed thread #6:
//          Background thread: True
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #3:
//          Background thread: True
//          Thread pool thread: True
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #4:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US
//       
//       Managed thread #1:
//          Background thread: False
//          Thread pool thread: False
//          Priority: Normal
//          Culture: en-US
//          UI culture: en-US

Foreground and background threads

Instances of the Thread class represent either foreground threads or background threads. Background threads are identical to foreground threads with one exception: a background thread does not keep a process running if all foreground threads have terminated. Once all foreground threads have been stopped, the runtime stops all background threads and shuts down.

By default, the following threads execute in the foreground:

  • The main application thread.

  • All threads created by calling a Thread class constructor.

The following threads execute in the background by default:

  • Thread pool threads, which are a pool of worker threads maintained by the runtime. You can configure the thread pool and schedule work on thread pool threads by using the ThreadPool class.

    System_CAPS_noteNote

    Task-based asynchronous operations automatically execute on thread pool threads. Task-based asynchronous operations use the Taskand Task<TResult> classes to implement the task-based asynchronous pattern.

  • All threads that enter the managed execution environment from unmanaged code.

You can change a thread to execute in the background by setting the IsBackground property at any time. Background threads are useful for any operation that should continue as long as an application is running but should not prevent the application from terminating, such as monitoring file system changes or incoming socket connections.

The following example illustrates the difference between foreground and background threads. It is like the first example in the Starting a threadsection, except that it sets the thread to execute in the background before starting it. As the output shows, the loop is interrupted before it executes for five seconds.

using System;
using System.Diagnostics;
using System.Threading;

public class Example
{
   public static void Main()
   {
      var th = new Thread(ExecuteInForeground);
      th.IsBackground = true;
      th.Start();
      Thread.Sleep(1000);
      Console.WriteLine("Main thread ({0}) exiting...", 
                        Thread.CurrentThread.ManagedThreadId); 
   }

   private static void ExecuteInForeground()
   {
      DateTime start = DateTime.Now;
      var sw = Stopwatch.StartNew();
      Console.WriteLine("Thread {0}: {1}, Priority {2}", 
                        Thread.CurrentThread.ManagedThreadId,
                        Thread.CurrentThread.ThreadState,
                        Thread.CurrentThread.Priority);
      do { 
         Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", 
                           Thread.CurrentThread.ManagedThreadId,
                           sw.ElapsedMilliseconds / 1000.0);
         Thread.Sleep(500);
      } while (sw.ElapsedMilliseconds <= 5000);
      sw.Stop(); 
   }
}
// The example displays output like the following:
//       Thread 3: Background, Priority Normal
//       Thread 3: Elapsed 0.00 seconds
//       Thread 3: Elapsed 0.51 seconds
//       Main thread (1) exiting...

Culture and threads

Each thread has a culture, represented by the CurrentCulture property, and a UI culture, represented by the CurrentUICulture property. The current culture supports such culture-sensitive operations as parsing and formatting, string comparison and sorting, and also controls the writing system and calendar used by a thread. The current UI culture provides for culture-sensitive retrieval of resources in resource files.

When a new thread is instantiated, its culture and UI culture are defined by the current system culture and UI culture, and not by the culture and UI culture of the thread from which the new thread is created. This means, for example, that if the current system culture is English (United States) and the current culture of the primary application thread is French (France), the culture of a new thread created by calling theThread(ParameterizedThreadStart) constructor from the primary thread is English (United States), and not French (France). For more information, see the "Culture and threads" section of the CultureInfo class topic.

System_CAPS_importantImportant

This is not true of threads that execute asynchronous operations for apps that target the .NET Framework 4.6 and later versions, In this case, the culture and UI culture is part of an asynchronous operations' context; the thread on which an asynchronous operation executes by default inherits the culture and UI culture of the thread from which the asynchronous operation was launched. For more information, see the "Culture and task-based asynchronous operations" section of the CultureInfo class topic.

You can do either of the following to ensure that all of the threads executing in an application share the same culture and UI culture:

For more information and examples, see the "Culture and threads" section of the CultureInfo class topic.

Getting information about and controlling threads

You can retrieve a number of property values that provide information about a thread. In some cases, you can also set these property values to control the operation of the thread. These thread properties include:

  • A name. Name is a write-once property that you can use to identify a thread. Its default value is null.

  • A hash code, which you can retrieve by calling the GetHashCode method. The hash code can be used to uniquely identify a thread; for the lifetime of your thread, its hash code will not collide with the value from any other thread, regardless of the application domain from which you obtain the value.

  • A thread ID. The value of the read-only ManagedThreadId property is assigned by the runtime and uniquely identifies a thread within its process.

    System_CAPS_noteNote

    An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

  • The thread's current state. For the duration of its existence, a thread is always in one or more of the states defined by the ThreadStateproperty.

  • A scheduling priority level, which is defined by the ThreadPriority property. Although you can set this value to request a thread's priority, it is not guaranteed to be honored by the operating system.

  • The read-only IsThreadPoolThread property, which indicates whether a thread is a thread pool thread.

  • The IsBackground property. For more information, see the Foreground and background threads section.

Accessing the source code for the Thread class

To view the .NET Framework source code for the Thread class, see the Reference Source. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructions.

Examples

The following example demonstrates simple threading functionality.

using System;
using System.Threading;

// Simple threading scenario:  Start a static method running
// on a second thread.
public class ThreadExample {
    // The ThreadProc method is called when the thread starts.
    // It loops ten times, writing to the console and yielding 
    // the rest of its time slice each time, and then ends.
    public static void ThreadProc() {
        for (int i = 0; i < 10; i++) {
            Console.WriteLine("ThreadProc: {0}", i);
            // Yield the rest of the time slice.
            Thread.Sleep(0);
        }
    }

    public static void Main() {
        Console.WriteLine("Main thread: Start a second thread.");
        // The constructor for the Thread class requires a ThreadStart 
        // delegate that represents the method to be executed on the 
        // thread.  C# simplifies the creation of this delegate.
        Thread t = new Thread(new ThreadStart(ThreadProc));

        // Start ThreadProc.  Note that on a uniprocessor, the new 
        // thread does not get any processor time until the main thread 
        // is preempted or yields.  Uncomment the Thread.Sleep that 
        // follows t.Start() to see the difference.
        t.Start();
        //Thread.Sleep(0);

        for (int i = 0; i < 4; i++) {
            Console.WriteLine("Main thread: Do some work.");
            Thread.Sleep(0);
        }

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
        t.Join();
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
        Console.ReadLine();
    }
}

This code produces output similar to the following:

[VB, C++, C#]
Main thread: Start a second thread.
Main thread: Do some work.
ThreadProc: 0
Main thread: Do some work.
ThreadProc: 1
Main thread: Do some work.
ThreadProc: 2
Main thread: Do some work.
ThreadProc: 3
Main thread: Call Join(), to wait until ThreadProc ends.
ThreadProc: 4
ThreadProc: 5
ThreadProc: 6
ThreadProc: 7
ThreadProc: 8
ThreadProc: 9
Main thread: ThreadProc.Join has returned.  Press Enter to end program.






Thread Constructor (ThreadStart)


Initializes a new instance of the Thread class.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Syntax

public Thread(
	ThreadStart start
)

Parameters

start
Type: System.Threading.ThreadStart

ThreadStart delegate that represents the methods to be invoked when this thread begins executing.

Exceptions

ExceptionCondition
ArgumentNullException

The start parameter is null.

Remarks

A thread does not begin executing when it is created. To schedule the thread for execution, call the Start method.

System_CAPS_noteNote

Visual Basic users can omit the ThreadStart constructor when creating a thread. Use the AddressOf operator when passing your method for example Dim t As New Thread(AddressOf ThreadProc). Visual Basic automatically calls the ThreadStart constructor.

Examples

The following code example shows how to create a thread that executes a static method.

using System;
using System.Threading;

class Test
{
    static void Main() 
    {
        Thread newThread = 
            new Thread(new ThreadStart(Work.DoWork));
        newThread.Start();
    }
}

class Work 
{
    Work() {}

    public static void DoWork() {}
}

The following code example shows how to create a thread that executes an instance method.

using System;
using System.Threading;

class Test
{
    static void Main() 
    {
        Work threadWork = new Work();
        Thread newThread = 
            new Thread(new ThreadStart(threadWork.DoWork));
        newThread.Start();
    }
}

class Work 
{
    public Work() {}

    public void DoWork() {}
}





Thread Constructor (ParameterizedThreadStart)


Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Syntax

public Thread(
	ParameterizedThreadStart start
)

Parameters

start
Type: System.Threading.ParameterizedThreadStart

A delegate that represents the methods to be invoked when this thread begins executing.

Exceptions

ExceptionCondition
ArgumentNullException

start is null.

Remarks

A thread does not begin executing when it is created. To schedule the thread for execution, call the Start method. To pass a data object to the thread, use the Start(Object) method overload.

System_CAPS_noteNote

Visual Basic users can omit the ThreadStart constructor when creating a thread. Use the AddressOf operator when passing your method, for example Dim t As New Thread(AddressOf ThreadProc). Visual Basic automatically calls the ThreadStart constructor.

Examples

The following example shows the syntax for creating and using a ParameterizedThreadStart delegate with a static method and an instance method.

using System;
using System.Threading;

public class Work
{
    public static void Main()
    {
        // Start a thread that calls a parameterized static method.
        Thread newThread = new Thread(Work.DoWork);
        newThread.Start(42);

        // Start a thread that calls a parameterized instance method.
        Work w = new Work();
        newThread = new Thread(w.DoMoreWork);
        newThread.Start("The answer.");
    }

    public static void DoWork(object data)
    {
        Console.WriteLine("Static thread procedure. Data='{0}'",
            data);
    }

    public void DoMoreWork(object data)
    {
        Console.WriteLine("Instance thread procedure. Data='{0}'",
            data);
    }
}
// This example displays output like the following:
//       Static thread procedure. Data='42'
//       Instance thread procedure. Data='The answer.'






ThreadPool Class


https://msdn.microsoft.com/en-us/library/system.threading.threadpool(v=vs.110).aspx


Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Inheritance Hierarchy

System.Object
  System.Threading.ThreadPool


Remarks

Many applications create threads that spend a great deal of time in the sleeping state, waiting for an event to occur. Other threads might enter a sleeping state only to be awakened periodically to poll for a change or update status information. The thread pool enables you to use threads more efficiently by providing your application with a pool of worker threads that are managed by the system. Examples of operations that use thread pool threads include the following:

  • When you create a Task or Task<TResult> object to perform some task asynchronously, by default the task is scheduled to run on a thread pool thread.

  • Asynchronous timers use the thread pool. Thread pool threads execute callbacks from the System.Threading.Timer class and raise events from the System.Timers.Timer class.

  • When you use registered wait handles, a system thread monitors the status of the wait handles. When a wait operation completes, a worker thread from the thread pool executes the corresponding callback function.

  • When you call the QueueUserWorkItem method to queue a method for execution on a thread pool thread. You do this by passing the method a WaitCallback delegate. The delegate has the signature

    void WaitCallback(Object state)
    

    where state is an object that contains data to be used by the delegate. The actual data can be passed to the delegate by calling the QueueUserWorkItem(WaitCallback, Object) method.

System_CAPS_noteNote

The threads in the managed thread pool are background threads. That is, their IsBackground properties are true. This means that a ThreadPoolthread will not keep an application running after all foreground threads have exited.

System_CAPS_importantImportant

When the thread pool reuses a thread, it does not clear the data in thread local storage or in fields that are marked with the ThreadStaticAttributeattribute. Therefore, when a method examines thread local storage or fields that are marked with the ThreadStaticAttribute attribute, the values it finds might be left over from an earlier use of the thread pool thread.

You can also queue work items that are not related to a wait operation to the thread pool. To request that a work item be handled by a thread in the thread pool, call the QueueUserWorkItem method. This method takes as a parameter a reference to the method or delegate that will be called by the thread selected from the thread pool. There is no way to cancel a work item after it has been queued.

Timer-queue timers and registered wait operations also use the thread pool. Their callback functions are queued to the thread pool.

There is one thread pool per process. Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.

System_CAPS_noteNote

Unmanaged code that hosts the .NET Framework can change the size of the thread pool by using the CorSetMaxThreads function, defined in the mscoree.h file.

The thread pool provides new worker threads or I/O completion threads on demand until it reaches the minimum for each category. When a minimum is reached, the thread pool can create additional threads in that category or wait until some tasks complete. Beginning with the .NET Framework 4, the thread pool creates and destroys worker threads in order to optimize throughput, which is defined as the number of tasks that complete per unit of time. Too few threads might not make optimal use of available resources, whereas too many threads could increase resource contention.

System_CAPS_noteNote

When demand is low, the actual number of thread pool threads can fall below the minimum values.

You can use the GetMinThreads method to obtain these minimum values.

System_CAPS_cautionCaution

You can use the SetMinThreads method to increase the minimum number of threads. However, unnecessarily increasing these values can cause performance problems. If too many tasks start at the same time, all of them might appear to be slow. In most cases the thread pool will perform better with its own algorithm for allocating threads.

Examples

In the following example, the main application thread queues a method named ThreadProc to execute on a thread pool thread, sleeps for one second, and then exits. The ThreadProc method simply displays a message.

using System;
using System.Threading;

public class Example 
{
    public static void Main() 
    {
        // Queue the task.
        ThreadPool.QueueUserWorkItem(ThreadProc);
        Console.WriteLine("Main thread does some work, then sleeps.");
        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }

    // This thread procedure performs the task.
    static void ThreadProc(Object stateInfo) 
    {
        // No state object was passed to QueueUserWorkItem, so stateInfo is null.
        Console.WriteLine("Hello from the thread pool.");
    }
}
// The example displays output like the following:
//       Main thread does some work, then sleeps.
//       Hello from the thread pool.
//       Main thread exits.

If you comment out the call to the Thread.Sleep method, the main thread exits before method runs on the thread pool thread. The thread pool uses background threads, which do not keep the application running if all foreground threads have terminated. (This is a simple example of a race condition.)






ThreadPool.QueueUserWorkItem Method (WaitCallback)


Queues a method for execution. The method executes when a thread pool thread becomes available.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Syntax

public static bool QueueUserWorkItem(
	WaitCallback callBack
)

Parameters

callBack
Type: System.Threading.WaitCallback

WaitCallback that represents the method to be executed.

Return Value

Type: System.Boolean

true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

Exceptions

ExceptionCondition
ArgumentNullException

callBack is null.

NotSupportedException

The common language runtime (CLR) is hosted, and the host does not support this action.

Remarks

You can place data required by the queued method in the instance fields of the class in which the method is defined, or you can use the QueueUserWorkItem(WaitCallback, Object) overload that accepts an object containing the necessary data.

System_CAPS_noteNote

Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem. Visual Basic automatically calls the correct delegate constructor.

Version Information

In the .NET Framework version 2.0, the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. In earlier versions, the principal information is not propagated.

Examples

The following example uses the QueueUserWorkItem(WaitCallback) method overload to queue a task, which is represented by the ThreadProc method, to execute when a thread becomes available. No task information is supplied with this overload. Therefore, the information that is available to the ThreadProc method is limited to the object the method belongs to.

using System;
using System.Threading;

public class Example 
{
    public static void Main() 
    {
        // Queue the task.
        ThreadPool.QueueUserWorkItem(ThreadProc);
        Console.WriteLine("Main thread does some work, then sleeps.");
        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }

    // This thread procedure performs the task.
    static void ThreadProc(Object stateInfo) 
    {
        // No state object was passed to QueueUserWorkItem, so stateInfo is null.
        Console.WriteLine("Hello from the thread pool.");
    }
}
// The example displays output like the following:
//       Main thread does some work, then sleeps.
//       Hello from the thread pool.
//       Main thread exits.





ThreadPool.QueueUserWorkItem Method (WaitCallback, Object)


Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)

Syntax

public static bool QueueUserWorkItem(
	WaitCallback callBack,
	object state
)

Parameters

callBack
Type: System.Threading.WaitCallback

WaitCallback representing the method to execute.

state
Type: System.Object

An object containing data to be used by the method.

Return Value

Type: System.Boolean

true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

Exceptions

ExceptionCondition
NotSupportedException

The common language runtime (CLR) is hosted, and the host does not support this action.

ArgumentNullException

callBack is null.

Remarks

If the callback method requires complex data, you can define a class to contain the data.

System_CAPS_noteNote

Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem. Visual Basic automatically calls the correct delegate constructor.

Version Information

In the .NET Framework version 2.0, the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. In earlier versions, the principal information is not propagated.

Examples

The following example shows how to create an object that contains task information. It also demonstrates how to pass that object to a task that is queued for execution by the thread pool.

// This example shows how to create an object containing task
// information, and pass that object to a task queued for
// execution by the thread pool.
using System;
using System.Threading;

// TaskInfo holds state information for a task that will be
// executed by a ThreadPool thread.
public class TaskInfo 
    {
    // State information for the task.  These members
    // can be implemented as read-only properties, read/write
    // properties with validation, and so on, as required.
    public string Boilerplate;
    public int Value;

    // Public constructor provides an easy way to supply all
    // the information needed for the task.
    public TaskInfo(string text, int number) {
        Boilerplate = text;
        Value = number;
    }
}

public class Example {
    public static void Main()
    {
        // Create an object containing the information needed
        // for the task.
        TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);

        // Queue the task and data.
        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti);

        Console.WriteLine("Main thread does some work, then sleeps.");

        // If you comment out the Sleep, the main thread exits before
        // the ThreadPool task has a chance to run.  ThreadPool uses 
        // background threads, which do not keep the application 
        // running.  (This is a simple example of a race condition.)
        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }

    // The thread procedure performs the independent task, in this case
    // formatting and printing a very simple report.
    //
    static void ThreadProc(Object stateInfo) 
    {
        TaskInfo ti = (TaskInfo) stateInfo;
        Console.WriteLine(ti.Boilerplate, ti.Value); 
    }
}
// The example displays output like the following:
//       Main thread does some work, then sleeps.
//       This report displays the number 42.
//       Main thread exits.







WebClient Class


Provides common methods for sending data to and receiving data from a resource identified by a URI.

Namespace:   System.Net
Assembly:  System (in System.dll)

Inheritance Hierarchy

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Net.WebClient

Remarks

The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI.

The WebClient class uses the WebRequest class to provide access to resources. WebClient instances can access data with any WebRequestdescendant registered with the WebRequest.RegisterPrefix method.

System_CAPS_noteNote

By default, the .NET Framework supports URIs that begin with http:https:, ftp:, and file: scheme identifiers.

The following table describes WebClient methods for uploading data to a resource.

Method

Description

OpenWrite

Retrieves a Stream used to send data to the resource.

OpenWriteAsync

Retrieves a Stream used to send data to the resource, without blocking the calling thread.

UploadData

Sends a byte array to the resource and returns a Byte array containing any response.

UploadDataAsync

Sends a Byte array to the resource, without blocking the calling thread.

UploadFile

Sends a local file to the resource and returns a Byte array containing any response.

UploadFileAsync

Sends a local file to the resource, without blocking the calling thread.

UploadValues

Sends a NameValueCollection to the resource and returns a Byte array containing any response.

UploadValuesAsync

Sends a NameValueCollection to the resource and returns a Byte array containing any response, without blocking the calling thread.

UploadString

Sends a String to the resource, without blocking the calling thread.

UploadStringAsync

Sends a String to the resource, without blocking the calling thread.

The following table describes WebClient methods for downloading data from a resource.

Method

Description

OpenRead

Returns the data from a resource as a Stream.

OpenReadAsync

Returns the data from a resource, without blocking the calling thread.

DownloadData

Downloads data from a resource and returns a Byte array.

DownloadDataAsync

Downloads data from a resource and returns a Byte array, without blocking the calling thread.

DownloadFile

Downloads data from a resource to a local file.

DownloadFileAsync

Downloads data from a resource to a local file, without blocking the calling thread.

DownloadString

Downloads a String from a resource and returns a String.

DownloadStringAsync

Downloads a String from a resource, without blocking the calling thread.

You can use the CancelAsync method to cancel asynchronous operations that have not completed.

WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing.

AllowAutoRedirect is set to true in WebClient instances.

Notes to Inheritors:

Derived classes should call the base class implementation of WebClient to ensure the derived class works as expected.

Examples

The following code example takes the URI of a resource, retrieves it, and displays the response.

using System;
using System.Net;
using System.IO;

public class Test
{
    public static void Main (string[] args)
    {
        if (args == null || args.Length == 0)
        {
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
        }
        WebClient client = new WebClient ();

        // Add a user agent header in case the 
        // requested URI contains a query.

        client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

        Stream data = client.OpenRead (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close ();
        reader.Close ();
    }







GC Class


https://msdn.microsoft.com/en-us/library/system.gc(v=vs.110).aspx


Controls the system garbage collector, a service that automatically reclaims unused memory.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)


Remarks

The garbage collector is a common language runtime component that controls the allocation and release of managed memory. The methods in this class influence when garbage collection is performed on an object and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object.

The garbage collector tracks and reclaims objects allocated in managed memory. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the Collect method.

Garbage collection consists of the following steps:

  1. The garbage collector searches for managed objects that are referenced in managed code.

  2. The garbage collector tries to finalize objects that are not referenced.

  3. The garbage collector frees objects that are not referenced and reclaims their memory.

This topic includes the following sections:

The garbage collector and unmanaged resources
Object aging and generations
Disallowing garbage collection

The garbage collector and unmanaged resources

During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. However, the garbage collector does not recognize references to an object from unmanaged code, and might free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The KeepAlive method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code.

Aside from managed memory allocations, implementations of the garbage collector do not maintain information about resources held by an object, such as file handles or database connections. When a type uses unmanaged resources that must be released before instances of the type are reclaimed, the type can implement a finalizer.

In most cases, finalizers are implemented by overriding the Object.Finalize method; however, types written in C# or C++ implement destructors, which compilers turn into an override of Object.Finalize. In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing the object. However, the garbage collector is not required to call finalizers in all situations; for example, the SuppressFinalize method explicitly prevents an object's finalizer from being called. Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order in which finalizers are called for objects that reference each other but are otherwise available for garbage collection.

In scenarios where resources must be released at a specific time, classes can implement the IDisposable interface, which contains the IDisposable.Dispose method that performs resource management and cleanup tasks. Classes that implement Dispose must specify, as part of their class contract, if and when class consumers call the method to clean up the object. The garbage collector does not, by default, call the Dispose method; however, implementations of the Dispose method can call methods in the GC class to customize the finalization behavior of the garbage collector.

For more information on object finalization and the dispose pattern, see Cleaning Up Unmanaged Resources.

Object aging and generations

The garbage collector in the common language runtime supports object aging using generations. A generation is a unit of measure of the relative age of objects in memory. The generation number, or age, of an object indicates the generation to which an object belongs. Objects created more recently are part of newer generations, and have lower generation numbers than objects created earlier in the application life cycle. Objects in the most recent generation are in generation 0. This implementation of the garbage collector supports three generations of objects, generations 0, 1, and 2. You can retrieve the value of the MaxGeneration property to determine the maximum generation number supported by the system.

Object aging allows applications to target garbage collection at a specific set of generations rather than requiring the garbage collector to evaluate all generations. Overloads of the Collect method that include a generation parameter allow you to specify the oldest generation to be garbage collected.

Disallowing garbage collection

Starting with the .NET Framework 4.6, the garbage collector supports a no GC region latency mode that can be used during the execution of critical paths in which garbage collection can adversely affect an app's performance. The no GC region latency mode requires that you specify an amount of memory that can be allocated without interference from the garbage collector. If the runtime can allocate that memory, the runtime will not perform a garbage collection while code in the critical path is executing.

You define the beginning of the critical path of the no GC region by calling one of the overloads of the TryStartNoGCRegion. You specify the end of its critical path by calling the EndNoGCRegion method.

Examples

The following example uses several GC methods to get generation and memory information about a block of unused objects and print it to the console. The unused objects are then collected, and the resulting memory totals are displayed.

using System;

namespace GCCollectIntExample
{
    class MyGCCollectClass
    {
        private const long maxGarbage = 1000;

        static void Main()
        {
            MyGCCollectClass myGCCol = new MyGCCollectClass();

            // Determine the maximum number of generations the system
	    // garbage collector currently supports.
            Console.WriteLine("The highest generation is {0}", GC.MaxGeneration);

            myGCCol.MakeSomeGarbage();

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));

            // Determine the best available approximation of the number 
	    // of bytes currently allocated in managed memory.
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));

            // Perform a collection of generation 0 only.
            GC.Collect(0);

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));

            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));

            // Perform a collection of all generations up to and including 2.
            GC.Collect(2);

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
            Console.Read();
        }

        void MakeSomeGarbage()
        {
            Version vt;

            for(int i = 0; i < maxGarbage; i++)
            {
                // Create objects and release them to fill up memory
		// with unused objects.
                vt = new Version();
            }
        }
    }
}








GC.Collect()


https://msdn.microsoft.com/en-us/library/xe0c2357(v=vs.110).aspx


Forces an immediate garbage collection of all generations.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

public static void Collect()

Remarks

Use this method to try to reclaim all memory that is inaccessible. It performs a blocking garbage collection of all generations.

All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.

Starting with the .NET Framework 4.5.1, you can compact the large object heap (LOH) by setting the GCSettings.LargeObjectHeapCompactionMode property to GCLargeObjectHeapCompactionMode.CompactOnce before calling the Collect method, as the following example illustrates.

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();      

Examples

The following example demonstrates how to use the Collect method to perform a collection on all generations of memory. The code generates a number of unused objects, and then calls the Collect method to clean them from memory.

using System;

class MyGCCollectClass
{
   private const int maxGarbage = 1000;

   static void Main()
   {
      // Put some objects in memory.
      MyGCCollectClass.MakeSomeGarbage();
      Console.WriteLine("Memory used before collection:       {0:N0}", 
                        GC.GetTotalMemory(false));

      // Collect all generations of memory.
      GC.Collect();
      Console.WriteLine("Memory used after full collection:   {0:N0}", 
                        GC.GetTotalMemory(true));
   }

   static void MakeSomeGarbage()
   {
      Version vt;

      // Create objects and release them to fill up memory with unused objects.
      for(int i = 0; i < maxGarbage; i++) {
         vt = new Version();
      }
   }
}
// The output from the example resembles the following:
//       Memory used before collection:       79,392
//       Memory used after full collection:   52,640





GC.Collect(int)


https://msdn.microsoft.com/en-us/library/y46kxc5e(v=vs.110).aspx


Forces an immediate garbage collection from generation 0 through a specified generation.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

public static void Collect(
	int generation
)

Parameters

generation
Type: System.Int32

The number of the oldest generation to be garbage collected.

Exceptions

ExceptionCondition
ArgumentOutOfRangeException

generation is not valid.

Remarks

Use this method to try to reclaim memory that is inaccessible. However, using this method does not guarantee that all inaccessible memory in the specified generation is reclaimed.

If object aging is implemented, the garbage collector does not collect objects with a generation number that is higher than the specified generation. If object aging is not implemented, the garbage collector considers all objects during the garbage collection.

Use the MaxGeneration property to determine the maximum valid value of the generation parameter.

To have the garbage collector consider all objects regardless of their generation, use the version of this method that takes no parameters. To have the garbage collector reclaim objects based on a GCCollectionMode setting, use the GC.Collect(Int32, GCCollectionMode) method overload.

Examples

The following example demonstrates how to use the Collect method to perform a collection on individual layers of memory. The code generates a number of unused objects, and then calls the Collect method to clean them from memory.

using System;

namespace GCCollectIntExample
{
    class MyGCCollectClass
    {
        private const long maxGarbage = 1000;

        static void Main()
        {
            MyGCCollectClass myGCCol = new MyGCCollectClass();

            // Determine the maximum number of generations the system
	    // garbage collector currently supports.
            Console.WriteLine("The highest generation is {0}", GC.MaxGeneration);

            myGCCol.MakeSomeGarbage();

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));

            // Determine the best available approximation of the number 
	    // of bytes currently allocated in managed memory.
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));

            // Perform a collection of generation 0 only.
            GC.Collect(0);

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));

            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));

            // Perform a collection of all generations up to and including 2.
            GC.Collect(2);

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
            Console.Read();
        }

        void MakeSomeGarbage()
        {
            Version vt;

            for(int i = 0; i < maxGarbage; i++)
            {
                // Create objects and release them to fill up memory
		// with unused objects.
                vt = new Version();
            }
        }
    }
}





GC.GetTotalMemory(bool)


https://msdn.microsoft.com/en-us/library/system.gc.gettotalmemory(v=vs.110).aspx


Retrieves the number of bytes currently thought to be allocated. A parameter indicates whether this method can wait a short interval before returning, to allow the system to collect garbage and finalize objects.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

public static long GetTotalMemory(
	bool forceFullCollection
)

Parameters

forceFullCollection
Type: System.Boolean

true to indicate that this method can wait for garbage collection to occur before returning; otherwise, false.

Return Value

Type: System.Int64

A number that is the best available approximation of the number of bytes currently allocated in managed memory.

Remarks

If the forceFullCollection parameter is true, this method waits a short interval before returning while the system collects garbage and finalizes objects. The duration of the interval is an internally specified limit determined by the number of garbage collection cycles completed and the change in the amount of memory recovered between cycles. The garbage collector does not guarantee that all inaccessible memory is collected.

Examples

The following example demonstrates how to use the GetTotalMemory method to get and display the number of bytes currently allocated in managed memory.

using System;

namespace GCCollectIntExample
{
    class MyGCCollectClass
    {
        private const long maxGarbage = 1000;

        static void Main()
        {
            MyGCCollectClass myGCCol = new MyGCCollectClass();

            // Determine the maximum number of generations the system
	    // garbage collector currently supports.
            Console.WriteLine("The highest generation is {0}", GC.MaxGeneration);

            myGCCol.MakeSomeGarbage();

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));

            // Determine the best available approximation of the number 
	    // of bytes currently allocated in managed memory.
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));

            // Perform a collection of generation 0 only.
            GC.Collect(0);

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));

            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));

            // Perform a collection of all generations up to and including 2.
            GC.Collect(2);

            // Determine which generation myGCCol object is stored in.
            Console.WriteLine("Generation: {0}", GC.GetGeneration(myGCCol));
            Console.WriteLine("Total Memory: {0}", GC.GetTotalMemory(false));
            Console.Read();
        }

        void MakeSomeGarbage()
        {
            Version vt;

            for(int i = 0; i < maxGarbage; i++)
            {
                // Create objects and release them to fill up memory
		// with unused objects.
                vt = new Version();
            }
        }
    }
}





















'프로그래밍 > C#' 카테고리의 다른 글

클래스 종류 헤드라인  (0) 2017.01.04
C# Keywords - Types  (0) 2016.12.29
Operators  (0) 2016.11.14
IEnumerable Interface  (0) 2016.11.14
Predicate<T> Delegate  (0) 2016.10.18
:
Posted by 지훈2