In my project on WPF, there is a button, on LeftMouseDown, an event is triggered, in which after 3 seconds while the mouse button is held down, the method will be executed (send to the database), but if we release the left mouse button, another LaunchMapUp event will be executed. How in C # code to generate this behavior.

For clarity, add your code, without this manipulation

<Image Grid.Row="2" Grid.Column="1" RenderOptions.BitmapScalingMode="HighQuality"> <Image.Style> <Style TargetType="{x:Type Image}"> <Setter Property="Source" Value="/Images/Panel_3/Button_1.png" /> <Style.Triggers> <DataTrigger Binding="{Binding EngineStart}" Value="True"> <Setter Property="Source" Value="/Images/Panel_3/Button_1_Press.png" /> </DataTrigger> </Style.Triggers> </Style> </Image.Style> <i:Interaction.Triggers> <i:EventTrigger EventName="MouseLeftButtonDown"> <i:InvokeCommandAction Command="{Binding EngineStartOn}" /> </i:EventTrigger> <i:EventTrigger EventName="PreviewMouseLeftButtonUp"> <i:InvokeCommandAction Command="{Binding EngineStartDown}" /> </i:EventTrigger> </i:Interaction.Triggers> </Image> 

And viewmodel

  public Command EngineStartOn { get { return new Command(() => { //Выполнить такую манипуляцию спустя 3 секунды EngineStart = false; }); } } public Command EngineStartDown { get { return new Command(() => { //Оборвать выполнения функции если не прошло 3 секунды }); } } 

    1 answer 1

    Well, like this:

     CancellationTokenSource cts = null; async void ScheduleDatabaseUpdate() { if (cts != null) throw new InvalidOperationException("Update already scheduled"); cts = new CancellationTokenSource(); try { await Task.Delay(TimeSpan.FromSeconds(3), cts.Token); await Task.Run(() => <тут запись в базу>); } catch (OperationCanceledException) { } } void CancelPendingUpdate() { if (cts == null) throw new InvalidOperationException("No pending update"); cts.Cancel(); cts = null; } 

    ScheduleDatabaseUpdate call on click, CancelPendingUpdate on mouse release.

    • thanks, it works fine) - Ivan Prodaiko
    • @IvanProdaiko: Please! Glad it helped! - VladD