开发者

Callback method C#

开发者 https://www.devze.com 2023-02-24 04:30 出处:网络
I need to create a callback method for my Commit method, just to know when it finished. So anyone know how to do that, how can I be able to call the commmit, then subscribe to the callback event/metho

I need to create a callback method for my Commit method, just to know when it finished. So anyone know how to do that, how can I be able to call the commmit, then subscribe to the callback event/method to do开发者_JS百科 other stuff when it is done.


Typically, in C#, you would do this via an event. The most common method for handling this would be to use the Event-based Asynchronous Programming model. This would define your API, by convention, as:

public void YourMethodAsync() {}  // starts your method
public Event EventHandler<YourEventArgs> YourMethodCompleted; // Event used to receive completion notification

That being said, if you're developing for .NET 4, you might want to consider designing your method around the Task or Task<T> class, instead. Instead of creating a callback, you can return a Task directly. This allows your user to create a task continuation that runs when the operation completes. In addition, future versions of C# will allow the user to take advantage of the await and async keywords currently in CTP form to ease development.


Define the Commit method to accept parameter of type Action.

And then you can pass a function as callback parameter to the Commit method.

e.g:

public void Commit(Action CommitCallback)
{
    //Code to handle Commit
    CommitCallback();
}


.
.
.
.
//Somewhere in your code:

Commit(()=>{ Console.WriteLine("Commit finished");});

or have a method defined

Commit(CommitPostProcessing);

public void CommitPostProcessing()
{
    //Some code
}


You can use events but they can get messy quickly. So to use a callback let's say that your Commit method's signature currently looks something like this,

void Commit() { }

You can add a callback easily using a delegate, let's say you accept a parameter of type CommitResult in your callback,

void Commit(Action<CommitResult> callback) { }

You can use this multiple ways, first is with a lambda,

obj.Commit(result => Console.Write(result));

or with another method,

obj.Commit(CallbackMethod);

void CallbackMethod(CommitResult result)
{
    Console.WriteLine(result);
}


You need to use events.

 public class LongOperation
{
    public event EventHandler Committed;

    public void Commit()
    {
        //Do you stuff here.
        //Call OnComitted once finished.
        OnCommitted(new EventArgs());
    }

    protected void OnCommitted(EventArgs e)
    {
        EventHandler handler = Committed;
        if (handler != null) 
            handler(this, e);
    }
}

Use following code from calling object:

        LongOperation operation = new LongOperation();
        operation.Committed += new EventHandler(operation_Committed);
        operation.Commit();
...

    void operation_Committed(object sender, EventArgs e)
    {
        //Do extra stuff here....
    }


As suggested, you can use events, here is a primitive example:

public MyClass
{
    public event EventHandler Comitted;

    public void Commit()
    {
        //committing code
        if (Comitted != null)
        {
            Committed(this, new EventArgs());
        }
    }
}

The reason we check for null of Comitted is simply because it is a possibility that there be no subscribers. So, how to subscribe? You need a method whose signature matches that of the EventHandler type of the event, when this method fires it is your indicator that Commit completed, then using an instance of the type you need to delegate the event:

var myClass = new MyClass();
myClass.Committed += OnCommitted;
myClass.Commit();

void OnCommitted(object sender, EventArgs e)
{
    //event handler code
}


You could implement an Observer Pattern http://en.wikipedia.org/wiki/Observer_pattern and subscribe

You could use a delegate http://msdn.microsoft.com/en-us/library/018hxwa8.aspx to call

You could create an event that gets triggered http://msdn.microsoft.com/en-us/library/awbftdfh.aspx and invoke it

Probably some other ways, those are the three off the top of my head.

0

精彩评论

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