• 0

Is it just me or do you hate the new await system?


Question

If I just want to call a web service function and have it return a class for me, why does visual studio force me to use the await/async features? I hate them personally. They are not easier to use as microsoft claims (at least not for someone who has never used them). I just simply want to say MyCustomResponse x = this.gl_client.GetCustomResponse(new Request() { }); I don't want to have to write a Task<MyCustomResponse> x = this.GetCustomResponse(...); and have to write an async method for it. That is the worst design I've ever heard of. What am I missing here? Like I want to simulate creating a user on the server side by calling a function.

Here is what I have to do so far:


private void xCreateNewAccBtn_Click(object sender, RoutedEventArgs e)
		{
			Task&lt;CreateNewUserResponse&gt; res = this.GetCreateNewUserResponse();
		}

		async Task&lt;CreateNewUserResponse&gt; GetCreateNewUserResponse()
		{
			Task&lt;CreateNewUserResponse&gt; getRes = this.gl_client.CreateNewUserAsync(new CreateNewUserRequest());

			CreateNewUserResponse res = await getRes;
			return res;
		}

That is easier then CreateNewUserResponse res = this.gl_client.CreateNewUser();? I'm sorry it's not. In .NET 4.0/regular WPF I can just call the functions synchronously and be happy. Or create a thread if it's super hungry for resources/time.

6 answers to this question

Recommended Posts

  • 0

I like it. There are a few places where it makes it a little more complicated such as if you are updating the UI from a background thread will cause some cross thread exceptions, but it is certainly not a problem in the case you are giving. You could easily call your code in the click method like this:

private void xCreateNewAccBtn_Click(object sender, RoutedEventArgs e)

{

CreateNewUserResponse res = await this.gl_client.CreateNewUserAsync(...);

}

You don't need a separate method, you do not need to deal with Task objects, just put the await keyword before the method call and it handles the threading properly. It also allows you to run multiple async tasks at the same time. For example, a program I am working on needs to hit multiple servers at once to download data. I could sequentially call to each server to get data, but it takes a long time to do so. To make it run faster, I call each server without the await keyword, store the returned Task objects into a list, and then call this code:

Task.WhenAll(listOfTasks.ToArray());

This way, pinging the servers will run on a separate thread and execution will not continue until calling each server is completed, all without blocking the UI. In one test scenario calling the servers sequentially was taking around 100 seconds, calling them all at once now takes about 8 seconds and I did not need to mess around with creating and managing my own threads. Calling a web server can take a while to run, and if the user is not connected to the internet or the server is down, you need to wait for the network timeout which will block the UI. That is not a problem with async/await in the dev model.

  • 0

<p>When I call that the way you have it throws an error.Error<span class="Apple-tab-span" style="white-space:pre"> </span>1<span class="Apple-tab-span" style="white-space:pre"> </span>Cannot implicitly convert type 'TestStoreApp.TestSvc.CreateNewUserResponse' to 'System.Threading.Tasks.Task<TestStoreApp.TestSvc.GetUserPubKeyResponse>'<span class="Apple-tab-span" style="white-space:pre"> </span>C:\Users\Test User\Documents\Visual Studio 2012\Projects\TestSaleStoreApp\TestStoreApp\RegisterNewUserScrn.xaml.cs<span class="Apple-tab-span" style="white-space:pre"> </span>41<span class="Apple-tab-span" style="white-space:pre"> </span>50<span class="Apple-tab-span" style="white-space:pre"> </span>TestStoreApp</p>

<div>?</div>

  • 0

So I guess my question is then, what am I doing wrong when I enter: CreateNewUserReponse getRes = await this.gl_client.CreateNewUserAsync(new CreateNewUserRequest()); ? I have been googling this info and the examples are not really showing me what is wrong with my code. Is it different for me because I'm calling a web service?

  • 0
That is easier then CreateNewUserResponse res = this.gl_client.CreateNewUser();? I'm sorry it's not. In .NET 4.0/regular WPF I can just call the functions synchronously and be happy. Or create a thread if it's super hungry for resources/time.
It's not easier than doing things synchronously, it just makes it easier to do things asynchronously. And if you need to call an async method synchronously you just call .Wait() or .Result() on it like you would for any Task(T).

For a long CPU-bound operation, creating a Task(T) manually is still the way to go - it'll run on its own thread and not block your UI. My understanding of async/await is that it will schedule things to run on the same thread if possible, not another one, so it's only fit for I/O-bound operations like awaiting a request over a network or a disk drive.*

*EDIT: ok that's not entirely correct. By default, await will schedule the completion on the same thread, but you can still use it and have the completion running on a threadpool thread by wrapping the call in Task.Run():

Example of async method that is scheduled to run on the same thread (good for I/O bound operations):


async Task<string> GetResponse(Server s) {
return await s.GetResponseAsync();
}
[/CODE]

Example of async method scheduled on a threadpool thread (good for CPU-bound operations):

[CODE]
async Task<double> ComputeAverage(IEnumerable<double> i) {
return await Task.Run(() => i.Average());
}
[/CODE]

There. :)

See http://msdn.microsof...o/hh191443.aspx

[CODE]private void xCreateNewAccBtn_Click(object sender, RoutedEventArgs e)
{
CreateNewUserResponse res = await this.gl_client.CreateNewUserAsync(...);
}[/CODE]

That's invalid C# because you can only use await in methods marked with the async keyword. This might have been your problem sathenzar.

  • 0

Thanks for the input Dr_Asik :) Always helpful around the forum no matter where you go. I'm just glad I figured it out eventually. It was frustrating me. I never used the await system when microsoft was testing it because I thought to myself meh, this will take a while to become standard if it ever does. Boy was I in for a surprise lol.

This topic is now closed to further replies.
  • Posts

    • Apple reportedly looks to blacklisted Chinese memory chips as RAM prices climb by Karthik Mudaliar Image via Apple Apple is reportedly trying to get a clearance from the Trump administration to buy memory from ChangXin Memory Technologies (CXMT) to get some relief from soaring DRAM prices. As per a report by the Financial Times, Apple approached the Commerce Department more than a month ago and also spoke to other officials and allies in Washington. For starters, CXMT is a company that's already been placed on the Pentagon's list of Chinese military companies. The Chinese company is the country's top DRAM maker. For Apple, the timing is certainly awkward but not surprising. Tim Cook had recently warned that Apple would have to raise prices because AI companies are buying up large amounts of memory for data centers, and just like that, Apple raised MacBook and iPad prices. Micron also recently revealed that customers have committed billions of dollars to secure memory supply years in advance, which shows us how aggressive securing infrastructure has become. This gives suppliers such as Samsung, SK Hynix, and Micron more leverage, while pushing hardware makers to look for alternatives. CXMT is one of those alternatives, but not the simplest one. Apple has spent many years trying to diversify parts of its supply chain away from China, especially for final assembly, while still depending heavily on Chinese manufacturing and suppliers. Even domestic brands from China are moving towards CXMT and YMTC instead of relying on Samsung, Micron, and SK Hynix. For Apple, though, it would invite more scrutiny than local Chinese companies. For now, this is more like a lobbying effort rather than a confirmed supply deal. There's no official statement from either of the parties. What is clearer, though, is the pressure behind such a request. AI demand has certainly made hardware a bottleneck, and companies are trying everything they can to bring things back to normal, even if that means making politically sensitive choices. Source: Financial Times
    • I did test it a month or so back, but ... the results I expect to be on the first page are not there.
    • Neowin is saying these are good prices? Thats crazy. As others have said they are just ######. Time for big tech to bring down the prices for real not this fake crap.
    • The iFlyTek AINote 2 is among the thinnest E-Ink tablets. It has an EMR stylus, a built-in fingerprint reader, and plenty of built-in AI features. You had me until "and plenty of built-in AI features." That and any company that still does the iProduct naming trope is an immediate pass. It suggests the company isn't very imaginative or creative and is trying to piggyback off another company's success. Extremely lame. Also kind of expensive. Better choices at lower prices out there.
    • These are not "great" prices... just "less awful". Apparently "Those who forget the past are doomed to pay higher prices and think they've won."
  • Recent Achievements

    • Week One Done
      flexorcist earned a badge
      Week One Done
    • One Month Later
      Woland13 earned a badge
      One Month Later
    • Week One Done
      Woland13 earned a badge
      Week One Done
    • One Year In
      bernmeister earned a badge
      One Year In
    • Week One Done
      Scoobystu earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      486
    2. 2
      +Edouard
      220
    3. 3
      PsYcHoKiLLa
      147
    4. 4
      Steven P.
      74
    5. 5
      FloatingFatMan
      70
  • Tell a friend

    Love Neowin? Tell a friend!