What is the basic knowledge of C #

Source: Internet
Author: User
Tags apm

Asynchronous this concept just start contact, not so easy to accept, but need to use the place is really a lot of, just learning, also very confused forced to go a lot of detours, so here is necessary to summarize.
MSDN Document: https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/
The official profile:
The *.net framework provides three modes for performing asynchronous operations:
Asynchronous programming Model (APM) mode (also known as IAsyncResult mode) in which asynchronous operations require the Begin and end methods (for example, BeginWrite and EndWrite Asynchronous write operations). This mode is no longer recommended for new development. For more information, see Asynchronous Programming Model (APM).

Event-based Asynchronous mode (EAP), which requires a method with an async suffix, and also requires one or more events, an event handler delegate type, and a eventarg derived type. EAP is introduced in the. NET Framework 2.0. New developments are no longer recommended. For more information, see Event-based Asynchronous mode (EAP).

A task-based Asynchronous Pattern (TAP) that uses a single method to represent the start and finish of an asynchronous operation. The introduction of tap in the. NET Framework 4 is the recommended asynchronous programming method in the. NET Framework. Async and Wait keywords in C #, the Async and await operators in the Visual Basic language Add language support for tap. For more information, see task-based Asynchronous mode (TAP). *

2. Asynchronous Application Scenarios
In the running of the computer program, the calculation takes a certain amount of time, such as uploading large files, requesting data from clients, reading file stream, etc. if synchronization (synvronous) must wait for the task to complete before continuing the next task. Using an asynchronous (asynchronous) operation, a new thread is opened, not waiting for the asynchronous operation to complete before it executes the subsequent program. Compared to the advantages of asynchronous Programming: 1. Is a long time processing program, not the card interface, users can still operate the UI interface 2. Improve the efficiency of program operation, save CPU resources, provide system throughput.

3. Relationship of processes and threads
This interview is basically going to ask, in short:
A program will have a process and a thread, the process is allocated by the CPU scheduling resources, there is a complete virtual address space, independent of the existence of the thread, whereas the thread is dispatched by the process to dispatch, just part of the process, without its own address space, Share all the resources of the process with other threads in the process. A simple analogy is like a thread as a human parasite that cannot exist independently and must rely on human (process) nutrition (resources) to survive (execute)

4. The difference between async and multithreading
Asynchronous is relative synchronization, we know that asynchronous is the opening of a new thread, but and multithreading is not a concept, asynchronous equivalent to a person's "brain" can do the test paper, but also to see the film, while processing more than two different things. Multithreading is like multiple people doing different things.

One of the 5.c# async modes (BeginInvoke, EndInvoke method)
Method 1: Use the callback method to complete the asynchronous delegate
Let's start with an example of a delegate's asynchronous invocation, which first defines a string-type return value, a delegate of a string-type argument. Although this mode is not recommended to be used.

Class Program
{
Delegate string Sayhi (string name);//define Delegate
static void Main (string[] args)
{
Sayhi sayhi = new Sayhi (sayhiname);//Instantiation of Delegates
Sayhi ("Kobe Bryant");//General direct call
Sayhi. Invoke ("Zhang Lin");//Use the Invoke method to synchronize calls
asynchronous invocation
Sayhi. BeginInvoke ("Durant", (IAsyncResult ar) =
{
Sayhi. EndInvoke (AR);
Console.WriteLine ("Greeting successful End");
}, NULL);
}
public static string Sayhiname (string name)
{
Return "How is You" +name + "?";
}
}
The first two methods of invoking a delegate are synchronous, and the return value of the BeginInvoke method is the IAsyncResult type.
The parameter of the method consists of two parts, the previous (n) parameter is the argument of the delegate, the second-to-last argument also represents a delegate, which is a delegate of the. NET System definition (and Func, action-like), to see the definition of AsyncCallback

The function is: as a callback method to execute the call, it is worth noting that in the callback method, the EndInvoke method must be called to end the asynchronous call, EndInvoke is the result of getting the asynchronous call
The result of the above example debugging


Mode 2: Use polling
We begininvoke the delegate parameter to NULL, using the polling method

func<string, string> func = delegate (string name)
{
Thread.Sleep (2000);
Return "How is You" + name + "";
};
IAsyncResult ar = func. BeginInvoke ("Zhang Lin", null,null);
int i = 1;
while (!ar. iscompleted)
{
Console.WriteLine (200*i);
i++;
Thread.Sleep (200);
}
string result = Func. EndInvoke (AR);
Console.WriteLine (result);
Results:


6.c# Async Mode two await async
Async and await are a pair of keywords that are features of. NET 4.5. The main reason for the ease of use and flexibility in practical work is that asynchronous programming can be done in the same way as the write synchronization method, where the code structure is clear and does not care how to implement asynchronous programming.
In fact, it's important to note that the async is started with a new thread, but the await and async two keywords do not open a new thread, in order to prove this, a WinForm program is built, asynchronously fetching the picture and displaying it to PictureBox.

Public Form1 ()
{
InitializeComponent ();
This.label1.Text = "Main thread ID:" +THREAD.CURRENTTHREAD.MANAGEDTHREADID;
}
Private async void Button1_Click (object sender, EventArgs e)
{
String imageUrl = "https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=3850265187,1181041963&fm=173&s= 62e19a4722716a371eb097fb03009015&w=218&h=146&img. JPEG ";
HttpClient client = new HttpClient ();
var response =await Client. Getasync (IMAGEURL);
if (response. StatusCode = = System.Net.HttpStatusCode.OK)
{
var stream =await Response. Content.readasstreamasync ();
Image image = Bitmap.fromstream (stream,true);
This.label2.Text = "Thread ID:" + Thread.CurrentThread.ManagedThreadId;
This.pictureBox1.BackgroundImage = image;
}
}
In fact, do not have to look at the figure has already known the answer, the program run without reporting an exception, it has been stated that: await async two key to create a new thread at all. This involves an asynchronous update of the UI to the main thread, which is not much to say.
Results


Instructions for using the async await method:

return type: void, Task, task< generic type >
Async, await does not create a new thread, implements the wait effect, and must use both
The method body using this method also uses the Async keyword
Async Method Cases:

private static Async task<int> getvalueasync (int a)
{
Task.run a new thread is opened
Await Task.run (() =
{
Thread.Sleep (2000); Simulation Time-consuming
Console.WriteLine ("Getvalueasync method end, Thread ID:" + Thread.CurrentThread.ManagedThreadId);
A=a * A;
});
Console.WriteLine ("Thread ID:" + thread.currentthread.managedthreadid+ "Async method End");
return A;
}
To invoke an Async method:

Private async void Button1_Click (object sender, EventArgs e)
{
int result =await Getvalueasync (5);
This.label1.Text = "Result of asynchronous computation" + result + "Thread ID:" + Thread.CurrentThread.ManagedThreadId;
}

On the three-7.c# asynchronous way of task
The earlier understanding that async await is a feature of. NET 4.5, The task is the. net4.0 new feature, which is used to handle asynchronous programming, in fact, we need to know that the actual implementation of asynchronous operations or task new threads to implement, but does not mean to open a task, a thread, it is possible that a few tasks run on a thread, they are not one by one corresponding relationship, take full advantage of the thread, the next The case of the surface has been able to illustrate this point
Task creation
Task creation has two ways of running a task factory assignment immediately, one for direct instantiation. Here's an example of creating 10 task

static void Main (string[] args)
{
Enable threads in a thread pool to execute asynchronously
Task T1 = Task.Factory.StartNew (() =
{
Console.WriteLine ("Task1 start ... Thread ID: "+thread.currentthread.managedthreadid);
});
Task t2 = Task.Factory.StartNew (() =
{
Console.WriteLine ("Task2 start ... Thread ID: "+ Thread.CurrentThread.ManagedThreadId);
});
New instantiation Start
task t3 = new Task (() =
{
Console.WriteLine ("Task3 start ... Thread ID: "+ Thread.CurrentThread.ManagedThreadId);
});
T3. Start ();
Task T4 = Task.Factory.StartNew (() =
{
Console.WriteLine ("Task4 start ... Thread ID: "+ Thread.CurrentThread.ManagedThreadId);
});
Task T5 = Task.Factory.StartNew (() =
{
Console.WriteLine ("Task5 start ... Thread ID: "+ Thread.CurrentThread.ManagedThreadId);
});
Task T6 = Task.Factory.StartNew (() =
{
Console.WriteLine ("Task6 start ... Thread ID: "+ Thread.CurrentThread.ManagedThreadId);
});
Task t7 = Task.Factory.StartNew (() =
{
Console.WriteLine ("Task7 start ... Thread ID: "+ Thread.CurrentThread.ManagedThreadId);
});
Task T8 = Task.Factory.StartNew (() =
{
Console.WriteLine ("Task8 start ... Thread ID: "+ Thread.CurrentThread.ManagedThreadId);
});
Task T9 = Task.Factory.StartNew (() =
{
Console.WriteLine ("Task9 start ... Thread ID: "+ Thread.CurrentThread.ManagedThreadId);
});
Task T10 = Task.Factory.StartNew (() =
{
Console.WriteLine ("Task10 start ... Thread ID: "+ Thread.CurrentThread.ManagedThreadId);
});
Console.ReadLine ();
}

Created 10 tasks, we also proved from the results that the task and thread are not one by one corresponding relationships, the result


Task constructor


Task status
We create a task that calls his start, wait method

static void Main (string[] args)
{
var task = new Task (() = {
Console.WriteLine ("Task Creation succeeded");
});
Console.WriteLine ("Task not started:" +task. Status);
Task. Start ();
Console.WriteLine ("Task has started:" +task. Status);
Task. Wait ();
Console.WriteLine ("Task has been waiting for:" +task.) Status);
}

Results:

As we can see, the life cycle of a task is as follows:
Created: The state before the start of the instantiation has been instantiated
Waittingtorun: Indicates waiting for the allocation thread to execute to the task
Rantocompletion: Task Execution complete

Task Wait Tasks result
1.task.waitall from this literal meaning to wait for all tasks to complete, and the above example wait method waits for a task to finish very similar, let's take a look at a code:

var task1 = new Task (() =
{
System.Threading.Thread.Sleep (3000);
Console.WriteLine ("task1created");
}); var task2 = new Task (() =
{
System.Threading.Thread.Sleep (3000);
Console.WriteLine ("task2created");
});
Task1. Start ();
Task2. Start ();
Task.waitall (Task1, Task2);
Console.WriteLine ("All Tasks are done!");
Console.read ();

Result output:
task1created
task2created
All tasks are completed
In addition to the WaitAll method, there are some common methods

Task.waitany: Wait for any one task to execute down
Task.continuewith waits for the first task to complete auto-start, triggering the next task, which is the callback method triggered when the task completes
Task.getawaiter (). OnCompleted (Action Action): Getawaiter method gets the waiting person for the task, invokes the OnCompleted event, and fires when the task completes
Task Cancel

static void Main (string[] args)
{
var Source = new CancellationTokenSource ();
var token = source. Token;
Task T1 = Task.run (() =
{
Thread.Sleep (2000);
if (token. iscancellationrequested)
{
Console.WriteLine ("Task Canceled");
}
Thread.Sleep (1000);
},token);
Console.WriteLine (t1. Status);
Cancel a task
Source. Cancel ();
Console.WriteLine (t1. Status);
Console.ReadLine ();
}

What is the basic knowledge of C #

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.