Is it possible to await an event instead of another async method?

In my C#/XAML metro app, there’s a button which kicks off a long-running process. So, as recommended, I’m using async/await to make sure the UI thread doesn’t get blocked: private async void Button_Click_1(object sender, RoutedEventArgs e) { await GetResults(); } private async Task GetResults() { // Do lot of complex stuff that takes a long … Read more

Why would finding a type’s initializer throw a NullReferenceException?

This has got me stumped. I was trying to optimize some tests for Noda Time, where we have some type initializer checking. I thought I’d find out whether a type has a type initializer (static constructor or static variables with initializers) before loading everything into a new AppDomain. To my surprise, a small test of … Read more

Using ‘async’ in a console application in C# [duplicate]

This question already has answers here: Can’t specify the ‘async’ modifier on the ‘Main’ method of a console app (17 answers) Closed 5 years ago. I have this simple code: public static async Task<int> SumTwoOperationsAsync() { var firstTask = GetOperationOneAsync(); var secondTask = GetOperationTwoAsync(); return await firstTask + await secondTask; } private async Task<int> GetOperationOneAsync() … Read more

What’s the difference between Task.Start/Wait and Async/Await?

I may be missing something but what is the difference between doing: public void MyMethod() { Task t = Task.Factory.StartNew(DoSomethingThatTakesTime); t.Wait(); UpdateLabelToSayItsComplete(); } public async void MyMethod() { var result = Task.Factory.StartNew(DoSomethingThatTakesTime); await result; UpdateLabelToSayItsComplete(); } private void DoSomethingThatTakesTime() { Thread.Sleep(10000); } 6 Answers 6

Do HttpClient and HttpClientHandler have to be disposed between requests?

System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker). The using statement documentation says: As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. This answer uses this pattern: var baseAddress = new Uri(“http://example.com”); var cookieContainer = new CookieContainer(); using (var handler = new … Read more

How do I make calls to a REST API using C#?

This is the code I have so far: public class Class1 { private const string URL = “https://sub.domain.com/objects.json?api_key=123”; private const string DATA = @”{“”object””:{“”name””:””Name””}}”; static void Main(string[] args) { Class1.CreateObject(); } private static void CreateObject() { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = “POST”; request.ContentType = “application/json”; request.ContentLength = DATA.Length; StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII); … Read more