C# Language
C # 5.0 Caratteristiche
Ricerca…
Sintassi
Async e attesa
public Task MyTask Async () {doSomething (); }
attendo MyTaskAsync ();
public Task
<string>
MyStringTask Async () {return getSomeString (); }string MyString = attendi MyStringTaskAsync ();
Attributi informazioni sul chiamante
public void MyCallerAttributes (stringa MyMessage,
[CallerMemberName] string MemberName = "",
[CallerFilePath] string SourceFilePath = "",
[CallerLineNumber] int LineNumber = 0)
Trace.WriteLine ("My Message:" + MyMessage);
Trace.WriteLine ("Membro:" + MemberName);
Trace.WriteLine ("Percorso file di origine:" + SourceFilePath);
Trace.WriteLine ("Line Number:" + LineNumber);
Parametri
Metodo / modificatore con parametro | Dettagli |
---|---|
Type<T> | T è il tipo di ritorno |
Osservazioni
C # 5.0 è abbinato a Visual Studio .NET 2012
Async e attesa
async
e await
sono due operatori che hanno lo scopo di migliorare le prestazioni liberando Thread e attendendo il completamento delle operazioni prima di andare avanti.
Ecco un esempio di come ottenere una stringa prima di restituire la sua lunghezza:
//This method is async because:
//1. It has async and Task or Task<T> as modifiers
//2. It ends in "Async"
async Task<int> GetStringLengthAsync(string URL){
HttpClient client = new HttpClient();
//Sends a GET request and returns the response body as a string
Task<string> getString = client.GetStringAsync(URL);
//Waits for getString to complete before returning its length
string contents = await getString;
return contents.Length;
}
private async void doProcess(){
int length = await GetStringLengthAsync("http://example.com/");
//Waits for all the above to finish before printing the number
Console.WriteLine(length);
}
Ecco un altro esempio di download di un file e gestione di ciò che accade quando il progresso è cambiato e al termine del download (ci sono due modi per farlo):
Metodo 1:
//This one using async event handlers, but not async coupled with await
private void DownloadAndUpdateAsync(string uri, string DownloadLocation){
WebClient web = new WebClient();
//Assign the event handler
web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
web.DownloadFileCompleted += new AsyncCompletedEventHandler(FileCompleted);
//Download the file asynchronously
web.DownloadFileAsync(new Uri(uri), DownloadLocation);
}
//event called for when download progress has changed
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e){
//example code
int i = 0;
i++;
doSomething();
}
//event called for when download has finished
private void FileCompleted(object sender, AsyncCompletedEventArgs e){
Console.WriteLine("Completed!")
}
Metodo 2:
//however, this one does
//Refer to first example on why this method is async
private void DownloadAndUpdateAsync(string uri, string DownloadLocation){
WebClient web = new WebClient();
//Assign the event handler
web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
//Download the file async
web.DownloadFileAsync(new Uri(uri), DownloadLocation);
//Notice how there is no complete event, instead we're using techniques from the first example
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e){
int i = 0;
i++;
doSomething();
}
private void doProcess(){
//Wait for the download to finish
await DownloadAndUpdateAsync(new Uri("http://example.com/file"))
doSomething();
}
Attributi informazioni sul chiamante
Le CIA sono intese come un modo semplice per ottenere attributi da qualunque cosa stia chiamando il metodo mirato. C'è solo un modo per usarli e ci sono solo 3 attributi.
Esempio:
//This is the "calling method": the method that is calling the target method
public void doProcess()
{
GetMessageCallerAttributes("Show my attributes.");
}
//This is the target method
//There are only 3 caller attributes
public void GetMessageCallerAttributes(string message,
//gets the name of what is calling this method
[System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
//gets the path of the file in which the "calling method" is in
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
//gets the line number of the "calling method"
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
//Writes lines of all the attributes
System.Diagnostics.Trace.WriteLine("Message: " + message);
System.Diagnostics.Trace.WriteLine("Member: " + memberName);
System.Diagnostics.Trace.WriteLine("Source File Path: " + sourceFilePath);
System.Diagnostics.Trace.WriteLine("Line Number: " + sourceLineNumber);
}
Esempio di output:
//Message: Show my attributes.
//Member: doProcess
//Source File Path: c:\Path\To\The\File
//Line Number: 13