• 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

    • Putin was behind Farage/Brexit and behind Trump/MAGA. Different idiot lying beasts, same fascist master. Same screwed up results for both nations.
    • For me the Final Fantasy games, Langrisser I & II, Hardspace: Shipbreaker, Horizon Forbidden West Complete Edition, Metaphor: ReFantazio and LUNAR Remastered Collection
    • Limited Prime Day deal sees Amazon Echo Show 11 is at its lowest price yet by Ivan Jenic The Amazon Echo Show 11 is currently $149.99 on Amazon during Prime Day, down from $219.99. That's 32% off and $70 saved on Amazon's newest mid-size smart display (purchase link below). As its name suggests, the Echo Show 11 features a 11” Full-HD touchscreen, which is a decent upgrade over the Echo Show 8. It offers 60% more viewing area, which makes a genuine difference for recipes, calendars, video calls, or any other scenario where the smaller display can feel a bit cramped. The Show 11 is built around Alexa+, Amazon's more capable AI assistant that can handle natural conversation. You can make reservations, order groceries, and find content based on your preferences, instead of always having to give it precise commands. There’s also the Omnisense technology, which adds ambient awareness, allowing the device to trigger routines based on temperature, presence detection, or visual cues. Smart home control is built in without needing a separate hub, and the home screen doubles as a photo slideshow when not in use. Taking all of this into account, the Show 11 is a perfect smart addition to your kitchen counter or living room. At $149.99, this is a strong Prime Day buy for anyone already in the Amazon ecosystem or looking to build one out. Amazon Echo Show 11 - $149.99 | 32% off on Amazon Good to know This Amazon deal is U.S. specific, and not available in other regions unless specified. We only use first-party seller links (at the time of article publishing); ensure that you purchase from a first-party seller link only. Check out Today's Deals on Amazon | or our recent tech deals. Become a Prime member (for Students or SNAP) via Neowin Get Prime Access - Prime for half price (for qualifying Medicaid, EBT, SNAP) Subscribe to Prime Video, Audible Plus, Music Unlimited or Kindle Unlimited via Neowin As an Amazon Associate, we earn from qualifying purchases.
  • Recent Achievements

    • One Year In
      bernmeister earned a badge
      One Year In
    • Week One Done
      Scoobystu earned a badge
      Week One Done
    • Week One Done
      tuben earned a badge
      Week One Done
    • First Post
      OffsetAbs earned a badge
      First Post
    • Reacting Well
      OffsetAbs earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      465
    2. 2
      +Edouard
      217
    3. 3
      PsYcHoKiLLa
      157
    4. 4
      Steven P.
      74
    5. 5
      FloatingFatMan
      71
  • Tell a friend

    Love Neowin? Tell a friend!