开发者

Is my "design pattern" for asynchronous methods good? [closed]

开发者 https://www.devze.com 2023-03-18 04:32 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

When I'm writing a class which contains metho开发者_如何学编程ds that are probably going to be executed on another thread, then I prepare my class for async usage. I add events to the class as the following: methodProgressChanged methodCompleted

In the method(s), before every sub-operation (for example, iterations) I raise the ProgressChanged event with a custom EventArgs class. This custom class contains info about what sub-operation is beginning now, and what the result of the previous sub-operation was.

So executing the method on another thread is not the method's task, it's just reporting the progress.

And of course, when I execute my method, the caller takes care of subscriptions to the events.

Is this idea acceptable, or should I forgot it totally?


If you are in .NET 4.0, I would recommend looking into Task and Task to encapsulate your async functionality. Then you could return a Task from the method you want to be a like so:

public Task<MyClass> Foo()
{
    return new Task<MyClass>(() => 
    {
         ReportProgress();
         DoSubOperation1();
         ReportProgress();
         DoSubOperation2();
         // ...
         return myClass;
    });
}

If you don't care about a return type, you can use the non-generic task. Then, when you call Foo(), you can call ContinueWith on the Task to give it a method to call once the Task completes.

If you want progress, you will need to keep your progress event because that's custom to the method that you're writing.

But overall, Task is a nice encapsulation for async functionality that keeps you from having to repeat the same MyMethod() MyMethodCompleted() pattern over and over again.


It's a reasonable idea, but I think it might be overkill, just because you're making assumptions that your events will be subscribed to. That said, I don't think it really causes too many problems, so long as your event subscribers behave properly; it's just that doing this incurs a little bit of overhead that may be wasted effort. That said, I don't really see anything wrong with it other than the (small) amount of (potentially unfruitful) time put into adding / raising the events.

0

精彩评论

暂无评论...
验证码 换一张
取 消