简体   繁体   中英

C# BeginInvoke to use or not to use

I currently want to use call function B from function A to avoid blocking function A . I thought BeginInvoke seems to be the good solution.

But i came to a point of asking myself, do I really need this? Invoking an asynchronous thread wouldn't it be longer than actually executing the function by simply calling the function B from function A? Moreover what happen if my function A is looping faster than the execution of function B?

EDIT:

The use of this would be to do a Trace Debug function having the least impact on the the caller.

I am kind of lost, I would appreciate your help

Thank you very much

Making an asynchronous call only makes sense if the call takes a considerable time to execute.

If the method that you call just does something simple and then returns, then it will be quicker just to call it than to create another thread and start it.

If you are calling the method in a loop, then you should consider using the AsParallel method to do it. It will throttle the number of threads used to do the work, instead of blindly firing off a lot of threads.

Doing a call via BeginInvoke is anyway already legacy as there are already better mechanisms nowadays with async.

For instance following code executes some long running operation without blocking the GUI thread:

await Task.Run(() =>
{
    //do something that takes time.


}).ConfigureAwait(true);

you can leave out the ConfigureAwait(true); because true is the default. But I like to keep it in the code because it documents my intent to continue after the long running operation on the GUI thread.

There is a lot of information about async await patterns. Also here on stackexchange and some interesting howto's from Stephen Cleary. Just google around a bit, even the MSDN info is not bad at all.

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