C # multithreading (4)

Source: Internet
Author: User

I. Event-Based Asynchronous EBA)

EAP provides a simple way to use multi-threaded programming, and provides multi-threaded capabilities without explicitly opening or managing threads. At the same time, a model cancellation function is provided to securely update the properties of WPF and WindowsFormsControl.

EAP is just a model. These features must be implemented using actual code. Among the. NET Framework, the most obvious ones are the BackgroundWorker class and WebClient class. The method ending with * Async in these classes is executed asynchronously: they open a new thread and return the result to the called method, after the execution is Completed, the method ending with * Completed is called. This method automatically calls the Invoke method (in WPF and WindowForms ).

Ii. BackgroundWorker class

This is an auxiliary class in the namespace of System. ComponentModel, which is a general implementation of the EAP model. This class uses a thread pool and therefore cannot call the Abort method.

1. Use BackgroundWorker

First, instantiate a BackgroundWorker class object, and call the DoWork method to call the RunWorkerAsync method. A parameter of the object type can be provided.
  static BackgroundWorker _bw = new BackgroundWorker();   static void Main()  {    _bw.DoWork += bw_DoWork;    _bw.RunWorkerAsync ("Message to worker");    Console.ReadLine();  }   static void bw_DoWork (object sender, DoWorkEventArgs e)  {    // This is called on the worker thread    Console.WriteLine (e.Argument);        // writes "Message to worker"    // Perform time-consuming task...  }
The RunWorkerAsync method always transmits parameters to the DoWork method. At the same time, after the DoWork method is executed, there is a RunWorkerCompleted event to process the action after the execution. Support Progress Report: Required WorkerReportsProgressThe property is true and is periodically called in DoWork. ReportProgressMethod, and then process ProgressChangedEvent, through its event parameter attributes ProgressPercentage. The code in the ProgressChanged event can freely interact with the UI control, which is particularly useful for updating the progress bar. Exit report supported: Set workersuppscanscancellation to true. periodically check the CancellationPending attribute in DoWork. If it is true, set the Cancel attribute of the event parameter to true and return the result. (The working thread may set Cancel to true without prompting via CancellationPending-if it is too difficult to determine whether it can continue to run ); call CancelAsync to request Exit 2. Use BackgroundWorker to implement subclass. This class is not a sealed class. When writing a very time-consuming method, use a method that returns the BackgroundWorker subclass, pre-configuration completes asynchronous work, as long as the RunWorkerCompleted event and ProgressChanged event are processed. 3. Timer

The simplest way to periodically execute a method is to use a Timer, such as the Timer class in the System. Threading namespace. The thread timer uses the thread pool to allow multiple timers to be created without additional thread overhead. Timer is a fairly simple class, which has a constructor and two methods (this is a pleasure for minimalists ).

public sealed class Timer : MarshalByRefObject, IDisposable{  public Timer (TimerCallback tick, object state, 1st, subsequent);  public bool Change (1st, subsequent);   // To change the interval  public void Dispose();                // To kill the timer}1st = time to the first tick in milliseconds or a TimeSpansubsequent = subsequent intervals in milliseconds or a TimeSpan (use Timeout.Infinite for a one-off callback)

In the following example, the timer calls the Tick method five seconds later. It writes "tick..." and then writes one per second until the user clicks Enter:

using System;using System.Threading;  class Program {  static void Main() {    Timer tmr = new Timer (Tick, "tick...", 5000, 1000);    Console.ReadLine();    tmr.Dispose();         // End the timer  }    static void Tick (object data) {    // This runs on a pooled thread    Console.WriteLine (data);          // Writes "tick..."  }}

. NET framework provides another Timer class in the System. Timers namespace. It is fully packaged from System. Threading. Timer and provides additional convenience when using the same thread pool-the same underlying engine. The following is a summary of the added features:

  • Implements Component, allowing it to be placed in the Visual Studio designer
  • The Interval attribute replaces the Change method.
  • The Elapsed event replaces the callback delegate.
  • Enabled
  • The Start and Stop methods are provided. If you are confused about Enabled
  • AutoReset flag to indicate whether to loop (true by default)

    Example:

    using System;using System.Timers;   // Timers namespace rather than Threading  class SystemTimer {  static void Main() {    Timer tmr = new Timer();       // Doesn't require any args    tmr.Interval = 500;    tmr.Elapsed += tmr_Elapsed;    // Uses an event instead of a delegate    tmr.Start();                   // Start the timer    Console.ReadLine();    tmr.Stop();                    // Pause the timer    Console.ReadLine();    tmr.Start();                   // Resume the timer    Console.ReadLine();    tmr.Dispose();                 // Permanently stop the timer  }    static void tmr_Elapsed (object sender, EventArgs e) {    Console.WriteLine ("Tick");  }}


    . NET framework also provides the third timer-in the System. Windows. Forms namespace. Although it is similar to the System. Timers. Timer interface, there are fundamental differences in features. A Windows Forms timer cannot use a thread pool. Instead, it always triggers a "Tick" event on the thread that was originally created. Assuming this is the main thread-responsible for instantiating Forms and controls in all Windows forms programs, Timer events can operate forms and controls without violating thread security-or imposing the unit thread mode. Control. Invoke is not required. It is essentially a single-thread timer

    Windows Forms timers must be executed quickly to update user interfaces. Quick execution is very important because the Tick event is called by the main thread. If it is paused, the user interface will become unresponsive.

    Iv. Local Storage

    Each thread is isolated from other thread data storage, which is beneficial for the storage of "irrelevant regions". It supports the basic structure of the execution path, such as communication, transactions, and security token. It is very clumsy to pass the data through method parameters. Storing the data to a static domain means that the data can be shared by all threads.

    Thread. GetDataRead from the isolated data of a thread,Thread. SetDataWrite Data. The two methods need a LocalDataStoreSlot object to identify the memory slot-this is a string packaged from the name of a memory slot. You can use this name across all threads and they will get different values, let's look at this example:

    Class... {// The same LocalDataStoreSlot object can be used for cross-Thread LocalDataStoreSlot secSlot = Thread. getNamedDataSlot ("securityLevel"); // each Thread of this attribute has a different value int SecurityLevel {get {object data = Thread. getData (secSlot); return data = null? 0: (int) data; // null ==uninitialized} set {Thread. SetData (secSlot, value );}}


    Thread. FreeNamedDataSlot will release the given data slot, which exists across all threads-but only once, when all the objects with the same name LocalDataStoreSlot are reclaimed as garbage, it will exit the scope. This ensures that the thread does not get the data slot from the bottom of their feet-it also keeps referencing the LocalDataStoreSlot object in proper use.








Related Article

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.