简体   繁体   中英

Main thread finishing during asynchronous method call?

Just wondering, is it necessary to programmatically create a new thread in a situation where the main thread does not need, and should not, wait for an asynchronous method call to finish?

In this case the asynchronous call is made when saving some data to a database, but this is the second last thing the calling method does (the last thing is returning the data). So it seems pointless to wait (especially because some other method is waiting for the return data), but if the calling method finishes right after making the call, the async method may not execute properly at all.

What is the best practice in a situation like this? I'm currently bound to .NET 3.5.

The only time this would be a problem is if the "calling method" was the application entry-point (aka Main() ), and the process itself terminated. In that scenario, design your API such that you can elect to wait for completion if you need - this can be direct (having a return object that allows waiting), or indirect (supplying a callback which sets a ManualResetEvent or similar).

By definition, an async method call is already involving another thread, so you don't need to duplicate that (and indeed, shouldn't). You should, however, make sure that any necessary "End*" is invoked - typically via a callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM