I'm just starting with c# development, and i always strugled with asyncronous programming,Ii have a doubt about performing a task asyncrounously.
I have my own service capable of sending an email (not going into details but its working) and I want that the execution of that method runs asyncronously, I've been reading in msdn documentation about async and await.
I do want to send it asyncronously but i dont care about the result, I mean I dont want to specify an await statement. I was about to try it whithout it when I read from documentation
If an async method doesn’t use an await operator to mark a suspension point, the method executes as a synchronous method does, despite the async modifier.
So mi doubt would be, is that so? is there a way to achieve what I am looking for or it is a bad pactice/idea thinking in doing something like that. I hope i made my self clear. Thanks
Regarding what you read in the docs, think about this this way:
public async Task OuterMethod()
{
InnerMethod();
}
You've marked OuterMethod async, yet you're not doing any awaiting. The docs are simply saying that OuterMethod will run synchronously, and you may as well just mark it with void instead of async Task. However, the fact that OuterMethod runs synchronously doesn't change the nature of InnerMethod; it may well be asynchronous, and if you're not awaiting it, it will run fire-and-forget style, most likely on a background thread.
In your specific case, InnerMethod would be the method that sends the email. If you're certain you don't care whether sending the email succeeds or fails, I'd suggest calling SmtpClient.SendAsync without awaiting.
Related
I know it's a bad practice, but it would be helpful to know how to deal with certain cases.
In my case I'm trying to create some files, then read them. I'm wondering how can I wait for the creation to complete, before I try to read their containing directory, without using setTimeout and conditions?
A lot of NodeJS function have synchronous counterparts, you should look for those.
Have a look at the documentation for File System at https://nodejs.org/api/fs.html.
Do a page search for 'sync' and you can see that it offers many synchronous functions.
It's not just File System that offer this. The Child_process does the same, see https://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options for example.
If you can't find a native synchronous version of a function you need, the npm registry is a good place to look, a lot of times you can find a synchronous package there.
Good luck!
p.s. It's not always bad practice to write synchronous code in NodeJS, many CLI tools are synchronous for example.
You can use async await or promise to accomplish it
Example:-
async function f() {
return 1;
}
You can pass your method inside it. it will wait till your response comes
After looking at the AWS Lambda documentation and some stackoverflow questions (especially this one: Context vs Callback in AWS Lambda), I'm still a little confused what the purpose of callback or context.success() is. Also, what was the original reason behind having context.success() back when callback couldn't be used?
I'm asking because I was given a Lambda function that uses both calls, and I don't know why one was chosen over the other at a given point.
Thanks!
From this article:
Context.succeed [is] more than just bookkeeping – [it] cause[s] the
request to return after the current task completes and freeze[s] the
process immediately, even if other tasks remain in the Node.js event
loop... [On the other hand,] the callback waits for all the tasks
in the Node.js event loop to complete, just as it would if you ran
the function locally. If you chose to not use the callback parameter
in your code, then AWS Lambda implicitly calls it with a return value
of null. You can still use the Context methods to terminate the
function, but the callback approach of waiting for all tasks to
complete is more idiomatic to how Node.js behaves in general.*
Kind of a weird question, Imagine you have a situation where you need to run 10 SYNCRONOUS functions, it doesn't matter when they complete, you just want to know when all 10 are done: I.E.
f1()
f2()
f3()
...
f10()
doStuffWithResult();
Now, If you use promises like so, assuming you have rewrote each as promoises:
Promise.All([f1,f2,f3,f4,f5,f6,f7,f8,f9,f10])
.then(() => {
doStuffWithResult();
})
Would you see a performance increase? Theoretically, I want to say no because these functions are still synchronous, and everything is still running on one thread.
Thanks!
Would you see a performance increase?
No, what you are proposing would not be faster.
Promises do not create threads. All they do is provide a cooperative system for keeping track of when asynchronous operations are complete and then notifying interested parties of success or failure. They also provide services for propagating errors when asynchronous operations are nested.
And, your proposed Promise.all() code would not even work. You must pass an array of promises to Promise.all(), not an array of function references. In your example, your functions would not even be called.
And, if you changed your code to something that would actually execute, then it would likely be slower than just calling the synchronous functions directly because you'd be executing promise code and all .then() handlers execute on a future tick (not synchronously).
In node.js, the only way to execute synchronous things in parallel is to launch child processes (that can execute in parallel) or pass the operations to some native code that can use actual OS threads.
I am getting my hands on node.js and its NPM valuable service. I tried installing this package and, by reading the documentation, it says that to generate a short id, this code needed:
shortId.generate();
that means that to use the ID, I would need something like this.
var id = shortId.generate();
res.end(id);
I hope I am not making a mistake here, but I thought the correct way to do things asynchronously was to use callbacks? And do something like:
shortId.generate(function(val){
res.end(val);
});
Can anyone please help me clarifying this problem? Thanks in advance.
Yes, the code in your example is synchronous. Node.JS has strength from it's asynchronous code, but not absolutely everything is asynchronous.
Mostly, the asynchronous code is usful for blocking IO.
As you could see from that module source code it does not perform any i/o at all while generating the id.
Callbacks in node are used when i/o takes place, so the program does not wait until the operation is performed, giving a function to be called when the i/o finishes.
The shortId.generate function is blocking, so it doesn't provide a callback for the result.
This makes sense in this case, because the unique ID generation isn't a heavy operation. If it was, you could adjust the code to enable a callback methodology.
Callbacks are definitely common though! For example, your web application wants to save an object to the server. You could be non-blocking here by adding a callback to the save function, so you could return a response sooner than the object has been written to disk/cache.
I recommend reading art of node for some great examples of blocking vs. non-blocking. :)
Before I render a page, I have to make several requests to mongodb. Here is how I do it now (db.js is my database processing layer):
db.findUser(objid, function(result1){
db.findAuthor(objid, function(result2){
db.findSmthElse (objid, function(result3){
res.render('template', {
user: result1,
author: result2,
smthelse: result2
});
});
});
});
I do suppose such methos kills the idea of async. However I need to call res.render only after all the requests are processed. How to launch it async? Should I use async library as it was advised here: multiple async mongo request in nodejs or are there any more suitable solutions? Thanks.
I do suppose such methos kills the idea of async
No they don't. That is precisely how asynchronous I/O is supposed to work. However, I do feel your pain with chaining multiple async calls. Before you know it, you can have 6 or 7 nested anonymous async functions.
There are two criteria I would use before I consider using a library like async or promise.
Number of functions - this is somewhat subjective, but how many looks frustrating to you? You currently have 3 and if you are likely to stick to three, then another library is probably not worth the complexity. Again, this is subjective and totally my opinion.
Dependencies - if each method builds on the results of the previous one, then they cannot run in parallel. However, in your case, the three database queries are independent and only the res.render call depends on the chained functions. Your use case is a good candidate for async.parallel in this regard.
I hope this helps you make your decision