Loki
Loki

Reputation: 1368

click event reset in xamarin.ios

btnLog.TouchUpInside += async (sender, e) =>
{
    try
    {
        SomeAction();
    }
    catch (Exception exe)
    {
        Log(exe.message);
    }
};

If we click btnLog 2,3 time SomeAction() is getting called 2,3 times, I want to call it only once i mean the last call, How to reset that event, Thanks.

Upvotes: 0

Views: 207

Answers (2)

JoeTomks
JoeTomks

Reputation: 3276

There are a few ways to achieve what you require, so I'll list a couple of them.

The first is to simply disable the button at the start of it's click event and then re-enable it after the 'work' you need to do has completed, this ensures that the 'work' only gets ran through once at a time.

This can be done like so:

btnLog.TouchUpInside += async (sender, e) =>
{
    btnLog.isEnabled = false;

    try
    {
        SomeAction();
    }
    catch (Exception exe)
    {
        Log(exe.message);
    }

    btnLog.isEnabled = true;
};

Or alternatively you can use an Interlocked.CompareExchange

private CancellationTokenSource cts = new CancellationTokenSource();
private CancellationToken token = new CancellationToken();
private int running;

btnLog.TouchUpInside += async (sender, e) =>
{
    if (Interlocked.CompareExchange(ref running, 1, 0) == 0)
    {
        try
        {
            Task.Run(async () =>
            {
                if (!token.IsCancellationRequested)
                {
                    await doWork();
                    running = 0;
                    return;
                }
                running = 0;
            }, token);
        }
        catch (TaskCanceledException tcEx)
        {
            running = 0;
        }
    }
};

private Task doWork()
{
    //Async method
}

The above only proceeds to run the Task, if the int 'running' equals zero, it also adopts a cancellation token, should you wish to cancel the doWork asynchronous method on a page change etc. We use this a fair amount to manage Tasks across our platforms.

Upvotes: 1

Madalin Sisu
Madalin Sisu

Reputation: 92

You can unsubscribe that method by creating an EventHandler in order to use the method by its name:

EventHandler method = async (sender, e) =>
{
    try
    {
        SomeAction();
        btnLog.TouchUpInside -= method;
    }
    catch (Exception exe)
    {
        Log(exe.message);
    }
};
btnLog.TouchUpInside += method;

Upvotes: 0

Related Questions