• 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

    • What they really need to do is automatically spell "loses" and "lose" correctly since nobody seems to know how to anymore. Then they blame spellcheck/autocomplete and don't realize autocomplete is just filling in the word for them automatically so it was misspelled in the first place.
    • If someone chooses to continue using SB and therefore goes through the manual intervention in the thread, afterwards the BSOD problem is gone. Whether they then re-enable the task doesn't matter, they're done, though on such machines it might pay to keep it disabled in case the next update (if there is a next) causes the same problem. OTOH, if someone disables SB in the BIOS, the problem is also gone. Incidentally, I noticed that this task exists even on machines that don't support SB. It's just installed across the board...and runs. Doing what on such machines is a little hazy.
    • qBittorrent 5.2.2 by Razvan Serea The qBittorrent project aims to provide a Free Software alternative to µtorrent. qBittorrent is an advanced and multi-platform BitTorrent client with a nice user interface as well as a Web UI for remote control and an integrated search engine. qBittorrent aims to meet the needs of most users while using as little CPU and memory as possible. qBittorrent is a truly Open Source project, and as such, anyone can and should contribute to it. qBittorrent features: Polished µTorrent-like User Interface Well-integrated and extensible Search Engine Simultaneous search in most famous BitTorrent search sites Per-category-specific search requests (e.g. Books, Music, Movies) All Bittorrent extensions DHT, Peer Exchange, Full encryption, Magnet/BitComet URIs, ... Remote control through a Web user interface Nearly identical to the regular UI, all in Ajax Advanced control over trackers, peers and torrents Torrents queueing and prioritizing Torrent content selection and prioritizing UPnP / NAT-PMP port forwarding support Available in ~25 languages (Unicode support) Torrent creation tool Advanced RSS support with download filters (inc. regex) Bandwidth scheduler IP Filtering (eMule and PeerGuardian compatible) IPv6 compliant Available on most platforms: Linux, Mac OS X, Windows, OS/2, FreeBSD qBittorrent 5.2.2 changelog: FEATURE: Use D-Bus to show file in file managers (Chocobo1) #24340 BUGFIX: Fix friendlyUnitCompact precision calculation (vafada) #24323 BUGFIX: Remove all top-level folders (glassez) #24333 BUGFIX: Use proper API for checking exit status (Chocobo1) #24349 BUGFIX: Delete stale lockfile when hostname mismatch (TurboTheTurtle, glassez) #24363 BUGFIX: Fix wrong removal procedure of watched folder paths (Chocobo1) #24413 BUGFIX: Don't reannounce before interface changes are applied (glassez) #24447 BUGFIX: Use Latin script for Bosnian locale name (Andy Ye) #24342 WEBUI: Fix performance of global checkbox toggling (tehcneko) #24316 WEBUI: Fix Safari transfer list header misalignment (Piccirello) #24377 WEBUI: Fix error when submitting magnet before metadata loads (Piccirello) #24378 WEBUI: Use correct row id when updating Rss Downloader feed selection (Chocobo1) #24402 WEBUI: Use SameSite=Lax for session cookie to fix cross-site login (Piccirello) #24422 WEBUI: Bring back properties panel expand/collapse button (vafada) #24430 WEBAPI: Only use X-Forwarded-Host header when reverse proxy support is enabled (Chocobo1) #24457 RSSS: Fix "RSS Smart Episode Filter" RegEx (nathanon-akk, glassez) #24398 RSS: Fix previously matched episode format (glassez) #24452 WINDOWS: Fix Python fallback search path (TurboTheTurtle) #24325 WINDOWS: NSIS: Allow to install x64 binary on ARM64 (Chocobo1) #24358 Download: qBittorrent 5.2.2 | 41.1 MB (Open Source) Download: qBittorrent 64-bit installer (qt6) | 43.6 MB Links: qBittorrent Home page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Weechat. https://weechat.org/
  • Recent Achievements

    • Veteran
      branfont went up a rank
      Veteran
    • Reacting Well
      Almohandis earned a badge
      Reacting Well
    • First Post
      Cosminus earned a badge
      First Post
    • One Year In
      ThatGuyOnline earned a badge
      One Year In
    • Week One Done
      Jeroen Wilms earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      485
    2. 2
      +Edouard
      185
    3. 3
      PsYcHoKiLLa
      126
    4. 4
      Steven P.
      87
    5. 5
      neufuse
      72
  • Tell a friend

    Love Neowin? Tell a friend!