Lambda expression question

This forum is meant for questions and discussions about the X# language and tools
Post Reply
User avatar
SHirsch
Posts: 286
Joined: Tue Jan 30, 2018 8:23 am
Location: Germany

Lambda expression question

Post by SHirsch »

Hi all,

Code: Select all

ASYNC METHOD btnInstallServiceClick(sender AS Object , e AS EventArgs) AS VOID
    SELF:obtnInstallService:Enabled := FALSE
    AWAIT Task.Run(Action{ SELF , @InstallService() })
RETURN
PROTECT METHOD InstallService() AS VOID
    VAR helper := Helper{}
    helper:Install()
    SELF:CheckButtons()
RETURN
I would like to shorten this code to something like this:

Code: Select all

ASYNC METHOD btnInstallServiceClick(sender AS Object , e AS EventArgs) AS VOID
    SELF:obtnInstallService:Enabled := FALSE
    AWAIT Task.Run( { () => VAR helper := Helper{}; helper:Install(); SELF:CheckButtons() } )
RETURN
Is that possible? If yes, how?

Regards,
Stefan
NickFriend
Posts: 248
Joined: Fri Oct 14, 2016 7:09 am

Lambda expression question

Post by NickFriend »

Hi Stefan,

I can't help you with the syntax I'm afraid, but just an observation.

I'm guessing that CheckButtons() sets the state of some buttons on your screen after the service has been installed. If so, it may be better to move it to after the await call in btnInstallServiceClick. That way CheckButtons is called on the UI thread once the async task has completed. It's generally better to avoid updating the UI thread from inside a task.

HTH

Nick
User avatar
Chris
Posts: 4898
Joined: Thu Oct 08, 2015 7:48 am
Location: Greece

Lambda expression question

Post by Chris »

Hi Stefan,

Answering only about the syntax part (Nick has covered the rest!), first of all, you can also use a simpler syntax, instead of

AWAIT Task.Run(Action{ SELF , @InstallService() })

you can use

AWAIT Task.Run(Action{ InstallService })

(I know, the first one is auto created by XIDE)

and in order to put it all in all command, you can use

Code: Select all

AWAIT Task.Run(Action{;
                        { =>  // lambda expression start
                           VAR helper := Helper{}
                           helper:Install()
                           SELF:CheckButtons()
                        };    // lambda expression end
                     })
It is a little tricky to use the correct syntax, but the rule is to not use ";" inside the lambda expression, use it to separate lines outside it only (lambda expression is the thing inside "{ => }".

Chris
Chris Pyrgas

XSharp Development Team
chris(at)xsharp.eu
User avatar
SHirsch
Posts: 286
Joined: Tue Jan 30, 2018 8:23 am
Location: Germany

Lambda expression question

Post by SHirsch »

Hi Chris,

thanks, it is compiling now. Syntax was the important part. Style is a matter of opinion.
But I will change this part. I will open a new thread to discuss the UI part.

Regards,
Stefan
Post Reply