[C #] collaborative thread cancellation,

Source: Internet
Author: User

[C #] collaborative thread cancellation,

Microsoft. Net Framework provides a standard mode for canceling operations. This mode is collaborative, meaning that the operation you want to cancel must be displayed to support cancellation.

CLR provides two classes for us:

System. Threading. CancellationTokenSource

System. Threading. CancellationToken

The CancellationToken instance is a lightweight value type because it contains a reference to a single private field: CancellationTokenSource. In a computing operation restriction cycle, you can regularly call the IsCancellationRequested attribute of CancellationToken to check whether the cycle should be terminated in advance and then terminate the operation on the computer.

I attached my frequently used code:

CancellationTokenSource cancel = new CancellationTokenSource (); Task. Factory. StartNew () => {while (! Cancel. isCancellationRequested) {// do something}, cancel. token); // cancel. token-> CancellationToken // cancel the cancel operation. cancel (); cancel. dispose (); cancel = null;

This class can also be used if the thread pool is used

Public void main () {var cancel = new CancellationTokenSource (); ThreadPool. QueueUserWorkItem (_ => {while (! Cancel. isCancellationRequested) {// do something}); Thread. sleep (10*1000); // to make the loop more time cancel. cancel (); cancel. dispose ();}

This class also has a good place to use when calling the Cancel Method in the Custom callback function. We need to use the Register Method (new CancellationTokenSource () in CancellationToken (). token. register () =>{}), and you can Register a Token multiple times and run it in reverse order.

 

 var cancel = new CancellationTokenSource();            cancel.Token.Register(() =>            {                MessageBox.Show("Register3");            });            cancel.Token.Register(() =>            {                MessageBox.Show("Register");            });            cancel.Token.Register(() =>            {                MessageBox.Show("Register1");            });            cancel.Token.Register(() =>            {                MessageBox.Show("Register2");            });

Pop-up sequence: Register2, Register1, Register, Register3

To deregister the registration callback function, you need to use CancellationTokenRegistration (this will be returned when Register is called) with the following code:

CancellationTokenRegistration registration = cancel. Token. Register () => {MessageBox. Show ("Register2") ;}); registration. Dispose (); // you can cancel this operation.

If you cancel the task and run it again, only the other three are displayed, or the reverse order is displayed.

Finally, you can link another set of CancellationTokenSource to create a new CancellationTokenSource object. If the CancellationTokenSource of any link is canceled, the new CancellationTokenSource object will be automatically canceled with the code attached:

  public static void Go()        {            var cts1 = new CancellationTokenSource();            cts1.Token.Register(() => Console.WriteLine("cts1 canceled"));            var cts2 = new CancellationTokenSource();            cts2.Token.Register(() => Console.WriteLine("cts2 canceled"));            var linkedcts = CancellationTokenSource.CreateLinkedTokenSource(cts1.Token, cts2.Token);            linkedcts.Token.Register(() => Console.WriteLine("linkedcts canceled"));            cts2.Cancel();            Console.WriteLine("cts1:{0}  cts2:{1}  linkedcts:{2}",                cts1.IsCancellationRequested, cts2.IsCancellationRequested, linkedcts.IsCancellationRequested);        }

Because the cts2 object is canceled, the unique CTS is automatically canceled. Here, the CancellationTokenSource. CreateLinkedTokenSource overload is params CancellationToken []. Theoretically, no matter how many CancellationToken objects are added, it is acceptable.


What are the differences between the form parameters in C language and the real parameters?

Formal parameters and actual parameters
Function parameters can be divided into form parameters and real parameters. In this section, we will further introduce the characteristics of the form parameters and real parameters and their relationships. Parameters appear in the function definition and can be used in the entire function body. If you leave this function, you cannot use them. Real parameters appear in the main function. After the function is called, the real parameters cannot be used. Parameters and parameters are used for data transmission. When a function is called, the main function transfers the value of the real parameter to the shape parameter of the called function to transmit the data of the called function.
Function parameters and real parameters have the following features:
1. The parameter variable allocates memory units only when called. At the end of the call, the allocated memory units are immediately released. Therefore, the parameter is valid only within the function. After the function call ends, you cannot use this variable after returning the primary function.
2. real parameters can be constants, variables, expressions, functions, etc. No matter what type of real parameters are, they must have a definite value during function calling, in order to pass these values to the form parameter. Therefore, values should be pre-assigned, input, and other methods to obtain a definite value for the real parameter.
3. The number, type, and sequence of the real parameters and form parameters must be strictly consistent; otherwise, the Type Mismatch Error will occur.
4. Data Transmission in function calls is unidirectional. That is, the value of the real parameter can only be transmitted to the form parameter, but the value of the form parameter cannot be reversely transmitted to the real parameter. Therefore, the value of the form parameter changes during the function call process, but the value of the real parameter does not change.

[Example] describes this problem.
Main ()
{
Int n;
Printf ("input number \ n ");
Scanf ("% d", & n );
S (n );
Printf ("n = % d \ n", n );
}
Int s (int n)
{
Int I;
For (I = n-1; I> = 1; I --)
N = n + I;
Printf ("n = % d \ n", n );
}

This program defines a function s, which is used to evaluate the value of Σ ni. Input n value in the main function and use it as a real parameter. The parameter n is transmitted to the s function during the call. (Note that in this example, the object variables and object variables are all named n, but this is two different quantities with different scopes ). In the main function, use the printf statement to output the n value at a time. The n value is the value of the real parameter n. In function s, the printf statement is also used to output an n value, which is the final n value 0 of the form parameter. According to the running status, the input n value is 100. That is, the value of real parameter n is 100. When this value is passed to function s, the initial value of parameter n is also 100. During function execution, the value of parameter n is changed to 5050. After the main function is returned, the value of output parameter n is still 100. It can be seen that the value of the real parameter does not change with the parameter.

[C Language] Is there a function that can clear keys in the cache?

Fflush (stdin)
Clear standard input Cache

# Include "stdio. h"
Main ()
{
Char a, B;
Scanf ("% c", & );
// Fflush (stdin );
Scanf ("% c", & B );
Printf ("\ n % c", a, B );
}

You can try it. If there is no fflush (stdin), if you enter a string of characters "abcd", a = 'A', B = 'B'
If fflush (stdin) exists, after entering "abcd", the program continues to wait for the input, and then enters "efdfsd". The result is a = 'A', B = 'E'

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.