x秒后删除图像源

时间:2013-01-24 21:18:52

标签: wpf multithreading

我有一个WPF应用程序,它会在单击按钮时设置图像源 我想在经过这么多秒后清除图像源,比如15秒就过去了。 我怎样才能做到这一点? 我试图使用Thread.sleep,但它立即清除了源,然后暂停应用程序15秒

这是我对该方法的看法

 private void btnCapture_Click(object sender, RoutedEventArgs e)
 {  
    imgCapture.Source = //my image source;

    Thread.Sleep(15000);
    imgCapture.Source = null;

 }

我也试过

 private void btnCapture_Click(object sender, RoutedEventArgs e)
  {  
    imgCapture.Source = //my image source;


    imgCapture.Source = null;
     Thread thread = new Thread(new ThreadStart(clearSource));
        thread.Start();

  }

    private void clearSource()
    {
        Thread.Sleep(15000);
        imgCapture.Source = null;
    }

但是我收到错误说调用线程无法访问此对象,因为另一个线程拥有它 如何在15秒后清除图像源。 谢谢!

2 个答案:

答案 0 :(得分:4)

使用DispatcherTimer

DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(15) };

    // in constructor
    timer.Tick += OnTimerTick;

private void btnCapture_Click(object sender, RoutedEventArgs e)
{
    imgCapture.Source = //my image source;
    timer.Start();
}

private void OnTimerTick(object sender, EventArgs e)
{
    timer.Stop();
    imgCapture.Source = null;
}

答案 1 :(得分:0)

@Clemens答案很好,但为了满足我最近的RX恋物癖:

void btnCapture_Click(object sender, RoutedEventArgs e)
{
    imgCapture.Source = //my image source;
    Observable.Interval( TimeSpan.FromSeconds( 15 ) ).TimeInterval().Subscribe( _ => imgCapture.Source = null );
}