|
void SomeFunction()
{
backgroundworker bw = new backgroundworker;
bw.DoWork += (object, eventargs) =>
{
};
}
So what I'm asking is instead of having a separate method for DoWork, is it bad style to put it in the same method that the UI would call?
|
|
|
|
|
Daniel Sheets wrote: So what I'm asking is instead of having a separate method for DoWork, is it bad style to put it in the same method that the UI would call?
Not that I'm aware. A ThreadPool-thread with a delegate does seem more readable though;
void SomeFunction()
{
ThreadPool.QueueUserWorkItem(delegate {
});
}
|
|
|
|
|
That local BackgroundWorker is not likely to survive long enough to actually finish.
As soon as SomeFunction exits it will be available to be GC'd.
I know this is just a quick, throw-away example, but the many beginners on CP might see this and not think of this issue.
|
|
|
|
|
Thanks for the replies.
And Matt... yeah, it was just meant as a throw-away example.
Still a good point to point out the GC though.
|
|
|
|
|
Nothing wrong with that syntactically. But my preference is that if the method is more than a couple lines long, I like to break it out into it's own method so that readability and maintainability is a little easier.
I wasn't, now I am, then I won't be anymore.
|
|
|
|
|
If the "time consuming work" is more then a few lines, I'd say it is bad style. Its not bad style to call a method or mess around with the parameters, etc. That is often quite handy. For example, if you used the stock handler there, you couldn't pass in any arguments. Its often a lot more useful to do something like:
bw.DoWork += (x, y) => MyCustomMethod(someLocalObject1, someLocalObject2);
To be honest though, I've shied away from BackgroundWorker as I find async to be much cleaner.
|
|
|
|
|
If you are using VS 2010 and Framework 4, use Tasks, I have not used VS 2012, so probably async is better. I like to us lambda expressons even for more than a few lines, but obviously not too many lines. What would I consider too many, maybe 10. It keeps everything together.
|
|
|
|
|
I don't get it. What's the big deal with putting a lot of code inside of a lambda expression?
Is it a matter of preference? Readability? Adherence to a standard of coding?
|
|
|
|
|
I think that too many lines is the same as having too many lines in a method. To me it is being able to see everything together when you can.
|
|
|
|