using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;
namespace WPF_DelayCall
{
/// <summary>
/// MainWindow.xaml 的互動邏輯
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
swipeGIF.Visibility = System.Windows.Visibility.Visible;
//方法一:
DelayCall(2000, () =>
{
swipeGIF.Visibility = System.Windows.Visibility.Collapsed;
});
//方法二:
//StartCloseTimer();
}
public void DelayCall(int msec, Action fn)
{
// Grab the dispatcher from the current executing thread
Dispatcher d = Dispatcher.CurrentDispatcher;
// Tasks execute in a thread pool thread
new System.Threading.Tasks.Task(() =>
{
System.Threading.Thread.Sleep(msec); // delay
// use the dispatcher to asynchronously invoke the action
// back on the original thread
d.BeginInvoke(fn);
}).Start();
}
private void StartCloseTimer()
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(2); // 2秒
timer.Tick += TimerTick;
timer.Start();
}
private void TimerTick(object sender, EventArgs e)
{
DispatcherTimer timer = (DispatcherTimer)sender;
timer.Stop();
timer.Tick -= TimerTick;
swipeGIF.Visibility = System.Windows.Visibility.Collapsed;
}
}
}