Thread processing in .NET (2)

zhaozj2021-02-17  46

The .NET framework provides many objects that help you create and manage multithreaded applications. WaitHandle objects can help you respond to operations performed by other threads, especially when interacting with the non-hosting code. ThreadPool provides the best basic thread creation and management mechanisms for most tasks. Monitor, Mutex, Interlocked, and ReaderWriterlock provide mechanisms for synchronizing on a lower level. Timer is a very flexible way to trigger activities at a specific time interval. I / O asynchronous completion uses the thread pool to inform you after I / O work is completed, so that you can do other things during this.

Thread pool [c #]

The thread pool can be used to make more effectively utilize multiple threads based on the needs of the application. Many applications use multiple threads, but these threads often consume a lot of time in the sleep state to wait for the event. Other threads may go to sleep, and only regularly wake up with polling or update status information, and then enter the sleep state. With the thread pool, you can provide an application auxiliary thread pool that is managed by the system, allowing you to focus on application tasks instead of thread management. In fact, if you want to perform some shortest tasks that require multiple threads, use the ThreadPool class is the most convenient and best way to utilize multiple threads. Using the thread pool allows the system to optimize this to achieve better throughput not only for this process but also for other processes on your computer (without knowing it). Use the thread pool to make the system to optimize the thread time slice after considering all current processes on your computer.

The .NET framework uses a thread pool for several purposes: asynchronous calls, system.net socket connections, asynchronous I / O completion, and timers and registered wait operations, and the like.

The thread pool is used by calling ThreadPool.QueueUserWorkITEM (or from the non-hosting code) to the WaitCallback delegation to the WaitCallback delegation to the package to be added to the queue. You can also use ThreadPool.RegisterWaitForsingleObject and deliver WaitHandle (when signal or timeout is sent to it, it will trigger the work item related to WaitortormAllBack to the thread pool to the thread pool. In both cases, both the thread pool uses or creates a backbone thread to call the callback method.

If you know that the caller's stack is not related to all security checks performed during the queuing task execution, you can use unsafe methods ThreadPool.unsafeueueUserWorkItemWorkItem, ThreadPool.unsafeRegisterWaitforsingleObject. QueueUserWorkItem and RegisterWaitForsingleObject are captured in the stack of the callback, which will merge the thread pool thread when the thread thread starts the task. If you need a security check, you must check the entire stack. Although this check provides safe, it also has certain performance overhead. Use "unsafe" method call does not provide absolute security, but it will provide better performance.

There is only one threadpool object in the application domain, and the thread pool will be created when you first call ThreadPool.QueueUserWorkItem or when the timer or the registered wait operation will queue a callback method. A thread monitors all tasks that have been queued to the thread pool. When a task is completed, the thread in the thread pool will perform the corresponding callback method. Will not cancel it after queuing a work item.

The number of operations that can be queued to the thread pool is only limited by the available memory; however, the thread pool will enforce the limit of the number of threads allowed simultaneously in the process (which depends on the number of CPUs and other factors). Each thread uses the default stack size to run in the default priority and in the multi-threaded unit. If a thread is idle in the hosted code (if you are waiting for an event), the thread pool will insert another auxiliary thread to keep all processors keep busy. If all thread pool threads are always busy, the queue contains hangs, and the thread pool will create another auxiliary thread after a while. But the number of threads will never exceed the maximum. THREADPOOL is also switched to the correct Appdomain when performing ThreadPool callback. In several cases, it is suitable for creating and managing your own thread instead of using ThreadPool. You should create and manage your thread in the following cases:

If you need to make a task have a specific priority.

If you have tasks that may be running for a long time (and thus block other tasks).

If you need to place the thread into a single-line unit (all ThreadPool threads are in the multi-threaded unit).

If you need a stable identifier associated with the thread. For example, you may want to use a dedicated thread to abort the thread, hang it or discovery it by name.

The following code example uses the QueueUserWorkItem WorkItem and RegisterWaitForsingleObject method. The former is used to request calls to the ThreadFunc method twice at each cycle. The latter is used to register the AutoreteTevent to Threadpool. Then, the signal will be sent to AutoreteTevent in a certain loop, and ThreadPool will allocate a thread to call WaitThreadFunc.

[Visual Basic]

Imports system

Imports system.threading

Public Class Sensor

Private Shared A as INTEGER = 32

Private Shared S as [String] = "Initial String"

Public Shared Sub Main ()

DIM EV AS New AutoreteTevent (false)

Threadpool.registerWaitForsingleObject (EV, New Waitortimercallback (Addressof Waitthreadfunc), Nothing, 20000, False

DIM Count As Integer

For count = 1 to 5

Console.writeline ("Hello Everyone !!)

Console.writeline ("{0}, {1}", A, s)

ThreadPool.QueueUserWorkItem (New Waitcallback (Addressof Threadfunc), Count

ThreadPool.QueueUserWorkItem (New Waitcallback (Addressof Threadfunc), Count 1)

'Signal the Autoretevent, Which raises the threadpool to

'Invoke the WaitthreadFunc.

If count = 2 THEN

ev.set ()

END IF

Thread.sleep (1000)

Next count

End Sub 'Main

Public Shared Sub ThreadFunc (o As Object)

Console.writeline ("Threadpool: WorkItem Number: {0}, Values: {1}, {2}", O, A, S) SYNCLOCK S

S = "Replacement String"

End synclock

Console.writeline ("Threadpool Done. {0}", S)

End Sub 'Threadfunc

Public Shared Sub WaitthreadFunc (o As Object, Signaled AS Boolean)

IF not (o is nothing) THEN

Console.writeline ("**** threadpool: WaitworkItem Type: {0}, values: {1}, o.gettype (). Name, s)

Else

Console.writeline ("**** threadpool: WaitworkItem Value IS: {0}", S)

END IF

Synclock S

S = "waitortimer: Special Timerstring."

End synclock

'Demonstrates Use of interlocked to show locking on an INT32.

Interlocked.Increment (a)

End Sub 'WaitthreadFunc

End Class' Sensor

[C #]

Using system;

Using system.threading;

Public Class Sensor

{

Static int a = 32;

Static string s = "initial string";

Public static int main (string [] args) {

AutoreteEvent EV = New AutoreteEvent (false);

Threadpool.registerWaitforsingleObject (

EV,

New waitortimercallback (waitthreadfunc),

NULL,

20000,

False

);

For (int count = 0; count <5; count) {

Console.writeline ("Hello Everyone !!);

Console.writeline ("{0}, {1}", A, s);

Threadpool.queueUserWorkItem (New Waitcallback (Threadfunc), 5);

ThreadPool.queueUserWorkItem (New Waitcallback (Threadfunc), 6);

// Signal the AutoreteTevent, Which raises the threereadpool to

// invoke the waitthreadfunc.

IF (count == 2)

ev.set ();

Thread.sleep (1000);

}

Return 0;

}

Public Static Void ThreadFunc (Object O) {

Console.writeline ("Threadpool: WorkItem Number: {0}, VALUES: {1}, {2}", O, A, S);

LOCK (s) {

S = "replacement string";

}

Console.writeline ("ThreadPool Done. {0}", S);

Public Static Void WaitthreadFunc (Object O, BooliLNALED) {

IF (o! = null) {

Console.Writeline ("**** threadpool: WaitworkItem Type: {0}, values: {1}", o.gettype (). Name, s);

}

Else

Console.writeline ("**** threadpool: WaitworkItem Value IS: {0}", s);

Lock (s)

{

S = "waitorTimer: Special Timerstring.";

}

// Demonstrates use of interlocked to show locking on an Int32.

Interlocked.Increment (Ref a);

}

}

转载请注明原文地址:https://www.9cbs.com/read-28547.html

New Post(0)