• 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

    • You've tried DuckDuckGo and Brave Search, now get serious with SearXNG by Paul Hill Over the last decade, it has become quite trendy to dump Google Search in favor of privacy-preserving alternatives such as DuckDuckGo, Startpage, and Brave Search. These search engines have done a very good job at highlighting dodgy practices by Google, such as adjusting search results based on what it thinks you’ll like (filter bubble) and stalking you around the web to advertise to you. While these search engines are good starting points when compared to non-private services like Google, there are still quite a few issues with them. For example, both DuckDuckGo and Brave Search require running non-free JavaScript in your web browser, which is comparable to running proprietary software on your computer, meaning you can be sure about what it’s actually doing in the background. Another issue is that these search engines are hosted on the respective companies’ servers, and you are using a service that you don’t control. Finally, DuckDuckGo, while offering privacy features, relies heavily on Microsoft’s infrastructure for its results and, in the past, has permitted Microsoft tracking scripts. If you are looking for a more private search solution than DuckDuckGo, Brave Search, and Startpage, then I recommend taking a look at SearXNG. It is a privacy-respecting metasearch engine that can be used via different public instances, which is useful for mobile users, or you can install it on your computer or server and run it locally with maximum control. Unlike Google, Bing, or Brave Search, which crawl the web and have their own search indexes, SearXNG is a metasearch engine, meaning it taps other search engines, stripping your identifying data, such as IP address, user agent, and cookies, in the process. Your search query is sent to the other search engines you enable before aggregating the results. SearXNG has deployment flexibility. If you are a casual user or a mobile user and don’t want to run SearXNG locally, you can use a public instance that is hosted by someone else. The main problem with this is that you are putting trust in the maintainer of the instance regarding stuff like logs that they may keep; good hosts should have a privacy policy explaining their policies. If you are trying to use SearXNG, you can also install the software on your device and then head to 127.0.0.1:8080 in your browser and search from there. While you don’t have to worry about a third-party admin like the public instances, search engines could ultimately block your IP address if they frown on you pulling in their search results locally. If you want to run it locally, it’s a good idea to use proxies or VPNs to hide your actual IP. You don’t have to worry about this with a public instance, as search engines never see your IP address. The main privacy benefit of using SearXNG is that it isolates your identity from the underlying engines that it’s capable of searching, such as Google and Bing. These search engines will only see requests coming from a generic server, so they can’t profile you and create a bubble filter that influences what results you see. This also ensures that your search engine doesn’t turn into an echo chamber that prevents you from reading alternative points of view. As a free software project, you are allowed to inspect SearXNG to make sure there are no negative features bundled inside. This sets it apart from the privacy search engines mentioned earlier because you can’t check their source code. As a meta search engine, you are not restricted to getting results from one source. Due to the fact that it scrapes content from other websites, your SearXNG instance will periodically get blocked from different providers, so it’s good to select a range of sources as a backup. While enabling all of the services will give you great results, this can make searching slower. I am personally happy with slower searches for the best results, but you can always check which providers are slowing down your search from the search results page and disable them to speed things up. If you want decent results quickly, enable the main search providers such as Google, Brave, DuckDuckGo, Qwant, Bing, and Yahoo. This way, you get wide coverage without the latency. On the Engines tab in Preferences, do note that there are different tabs, such as General, Images, and Videos, with their own providers that can be toggled and are not covered by "Enable all" while on the General tab, so be sure to dig into each. Just a note, if you want to enable everything, press "Enable all" in one tab, then hit save at the bottom of the page, then do the next tab, and so on. If you press "Enable all", then do that in each tab, and then save, nothing will stick. When I had just some of the search engines enabled, I searched “define nefarious” and results came back with the definition of “define” - obviously that was a sucky result. However, when I had everything enabled, it found dictionary pages for the word “nefarious” and even had an inline definition on the sidebar, which is quite nice too - that was delivered by WolframAlpha for anyone wondering! Probably the worst thing about this meta search engine is that the engines you select are saved with a cookie, so you must enable them on every new device you use SearXNG on, including if you decide to go into incognito mode with your web browser. Honestly, I would say this is the most annoying aspect, and perhaps if your browser lets you choose a separate private browsing search engine, then it would be best to use DuckDuckGo for this portion of your browsing. Another weakness of SearXNG is the random blocking of it by search providers. When you are on the results page, expand the “Response time” box, and it will show things like “Suspended: too many requests” or “access denied”. This is why it is good to enable several providers so that there is always a fallback to get results from. I won’t pretend SearXNG will be for everyone, however, if you enable all of the providers and put up with the slower response time, the results can be really amazing. Even if you don’t want to use it as your daily driver, keeping a bookmark handy that links to it is a good idea if you ever feel like doing a deep dive into a niche topic where other search engines are just failing to bring up any good result, due to the amount of sources it looks on. If you’re interested in radical user control over the software you use, installing SearXNG locally can also be a good idea, but be prepared to be temporarily blocked from sites if you trigger bot sensors without a VPN. Personally, I’ve opted to use a public instance, rather than install it myself. If you want to use it via a public instance, head over to searx.space to find a provider. Let us know in the comments if you have used SearXNG or its predecessor, Searx. What do you think about the quality of the results?
    • Dear Neowin, If it is not too much trouble, can you start using the new-ish designations for Insider Preview? "Experimental" is different than "former Dev" as it can apply to different models, eg 26H1 or 26H2 etc, right? No need to seed confusion IMHO. And, please "finally" update your graphics. OK?
    • Did you see their FAQ, its quite good. Have a look in the Advanced section. https://delta.chat/en/help
    • Just install Linux Mint that is a real blessing and many times cheaper because you can continue using your old Windows computer/laptop with the latest Linux updates.
    • Interesting share -- however it does not make sense: Email messages get stored somewhere, so how is Delta Chat "based on email" and decentralized without actually storing anything? By Web3 standard practices, the various Relays would require dedicated storage to make messages available to the recipients (like a large series of message queue channels, akin to racks of traditional post office boxes)... and Contacts must be two-way confirmed in order for encryption keys to be exchanged (ostensibly every key-pair is uniquely bound between sender and recipient) and the Relays would preserve the public keys in order to facilitate message carriage... or every device stores all sorts of keys and contact info. All of this to say, decentralized messaging is like running Bluesky nodes except instead of discovering/browsing public feeds by various posters (at the given node) these Delta Chats would be relaying encrypted messages (via Relays) that only trusted recipients would have the appropriate decryption key (their own private key) to read it. But this doesn't solve the "it's like email" sales pitch. The only way it's like email is that there's encrypted binary stuff being transported from your app into the federated ether of Delta Chat Relays for others to decrypt (hopefully only the intended recipient)... but outside of this federated relays framework, it is absolutely nothing like email.
  • Recent Achievements

    • Week One Done
      Woland13 earned a badge
      Week One Done
    • One Month Later
      Woland13 earned a badge
      One Month Later
    • 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
  • Popular Contributors

    1. 1
      +primortal
      504
    2. 2
      +Edouard
      228
    3. 3
      PsYcHoKiLLa
      163
    4. 4
      Steven P.
      76
    5. 5
      FloatingFatMan
      71
  • Tell a friend

    Love Neowin? Tell a friend!