• 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

    • For some reason I suddenly have the urge to go shopping at Sears.
    • So I did a quick test based on 3+ different public instances from the litany at searx.space ... and it spins everything rather differently. It seems that SearXNG is a meta-search engine (queries multiple search indexes rather than only Google's or Bing's or Wikipedia's or Reddit's) that operates in two modes: > public instances ... each instance opens itself to outside users who piggyback on its cached search history; this instance's own identity becomes known/tracked but end-users are hidden similar to an anonymization proxy; this instance's querying of major search indexes may be API based [rated limited, blocked, etc.]). > private instances ... your private install/instance that itself queries multiple (configurable) search indexes of crawled web content; every major Search Engine associates all traffic to your private instance (so your traffic is tracked via network usages) but client-side tracking (your own browser/computer specs) is flushed because it's a "server" doing the querying rather than your browser. My test asked the same 1 question to the 3+ engines and they all returned vastly different results: some had CAPTCHA failures against Google, some had failures against Wikipedia, and the actual results were also different -- some had auto-complete enabled, others returned a wikipedia highlighted excerpt despite the Wikipedia failure (hinting at results being cached from previous keyword matching), and others just gave an Are-You-Human non-CAPTCHA loop before returning random results. So this begs the caveat: Search query results will vary based on which instance is used because every instance queries the other search indexes separate (and thus its results are influenced on that instance's aggregate search history and index-access limitations). The major distinctions for SearXNG versus DDG or Brave: > The search UI is 'untracked' since no UI trackers are baked-in which would phone home or lay cookies into your browser (for DDG/Brave usage stats), > There is no 'crawler' that canvasses the Internet to discover fresh content (it leaves that to the major search indexes), > Queries multiple search indexes ("meta-search engine") based on the configurations and usage history of the server instance, > Privacy-friendly due to its ability to shield user tracking via standing up a non-local server instance connectable to major VPN providers: queries would all appear to come from general VPN/Proxy providers rather than your private instance (whether installed locally or on your own VPS in the cloud). PS: I've previously come across specialized search engines of this nature that indexes searches across media assets like YT, OF, etc. SearXNG seems to be a good backbone...if the rate-limiting/captcha/etc. issues were resolved.
    • For a guy who claims to hate Farage and the ignorant, gullible, rightwing racist skinheads sponsored by Putin that his lies represent, you sure are quoting them time and time and time again, mate. I guess you're conveniently ignoring the fact that your country and commonwealth just happened to work much better when it was still part of the E.U.? Denial isn't just a river in Egypt.
    • Do you live in the U.K? Do any of the people here that are against the UK leaving the E.U, live in the U.K? If not then why are you bothered? If you do live here then it is a different thing . Brexit was a good idea, should have done it years before, it was done badly, but the idea was good. You are saying the same thing as remainers do, oh we did what Putin wanted, we listened to the lies and Farage. I hate Farage and never believed most of what he said, certainly did not believe the £350m a week for the NHS. But we did pay a lot of money to the E.U and yes some of it came back, but what is the point of paying it out for only some of it to come back? Get out of the E.U, no money to them and in theory we can use the money to do things in the country. I said in theory, but our governments are a total and complete waste of space. No matter what colour rosette they wear. You and others say it was a mistake and yet the two main parties in the U.K are not looking at rejoining the EU, I wonder why that is? I was not tricked by anyone. Makes no odds now, we are out and have been for 10 years, what we need is a decent government to run the country. All they do is shout at each other like a load of kids and seems to do nothing and make this country more into a police and nanny state. Getting more like China all the time.
    • 4TB TEAMGROUP MP44Q, 2TB T-Force G50, and 2TB WD My Passport SSDs drop to great prices by Fiza Ali Prime Day may be over, but there are still worthwhile storage deals available, including discounts on SSDs for shoppers who missed the event or are looking to upgrade their storage solution. Particularly, 2TB Western Digital My Passport, 2TB TEAMGROUP T-Force G50, and 4TB TEAMGROUP MP44Q SSD are selling at great prices with up to 23% off. The 2TB TEAMGROUP T-Force G50 is an M.2 2280 PCIe 4.0 x4 NVMe SSD with sequential read speeds of up to 5,000MB/s and sequential write speeds of up to 4,500MB/s. The drive has an endurance rating of 1,300 TBW (terabytes written) and features a DRAM-less design. The company specifies a mean time between failures (MTBF) of 3 million hours. The drive includes an "ultra-thin" graphene heat spreader that helps dissipate heat without significantly increasing the drive's thickness. It also supports S.M.A.R.T. monitoring, allowing compatible software to monitor drive health and operating status. The SSD is rated for operating temperatures from 0°C to 70°C, with a storage temperature range of -40°C to 85°C. The drive is backed by a five-year limited warranty as well. 2TB TEAMGROUP T-Force G50 SSD: $269.99 (Amazon US) The TEAMGROUP MP44Q is an M.2 2280 PCIe 4.0 x4 NVMe SSD that delivers sequential read speeds of up to 7,000MB/s and sequential write speeds of up to 5,900MB/s. It uses 3D QLC NAND flash memory to provide 4TB of storage capacity for games, applications, media files, and other data. The drive has an endurance rating of 2,000 TBW and an MTBF of 1.6 million hours. The SSD features a DRAM-less design and supports TEAMGROUP's S.M.A.R.T. monitoring software, allowing users to monitor drive health, temperature, and remaining lifespan. For thermal management, the MP44Q also includes an "ultra-thin" graphene heat spreader. It is designed to operate at temperatures between 0°C and 70°C and can be stored at temperatures ranging from -40°C to 85°C. The SSD is also backed by a five-year limited warranty. 4TB TEAMGROUP MP44Q SSD: $478.99 (Amazon US) The 2TB WD My Passport SSD connects via a USB-C port using the USB 3.2 Gen 2 interface. It delivers sequential read speeds of up to 1,050MB/s and sequential write speeds of up to 1,000MB/s through NVMe technology. In terms of security features, the drive includes password protection with 256-bit AES hardware encryption. The SSD is also designed to resist shock and vibration and is rated to withstand drops from heights of up to 6.5 feet. The recommended operating temperature range is 5°C to 35°C, while the non-operating temperature range is -20°C to 65°C. This drive is also backed by a five-year limited warranty. 2TB Western Digital My Passport SSD: $279.99 (Amazon US) 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

    • 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
      491
    2. 2
      +Edouard
      225
    3. 3
      PsYcHoKiLLa
      147
    4. 4
      Steven P.
      74
    5. 5
      FloatingFatMan
      71
  • Tell a friend

    Love Neowin? Tell a friend!