点击期间更新Windows Phone上的文本块

时间:2012-02-03 18:49:50

标签: multithreading windows-phone

我正在为Windows Phone 7.5(芒果)开发数据库应用程序。我尝试(在点按按钮期间)使用文本"正在搜索..."更新文本块。此按钮在大表中执行相当冗长的搜索,因此我想通知用户。但是我尝试的一切都失败了!这是我使用的代码片段之一。有没有办法实现这个目标?任何帮助,帮助我理解什么是错的将被赞赏。

private void btnSearch_Tap(object sender, GestureEventArgs e)
{
    workerThread = new Thread(new ThreadStart(turnVisibilityOn));
    workerThread.Start();
    while (!workerThread.IsAlive) ;
    Thread.Sleep(500);

    //Search database takes about 15 sec on windows phone device!
    Procedures[] results = CSDatabase.RunQuery<Procedures>(@"select Code, Description from tblLibraries where Description like '%" +
    textBox1.Text + "%' or Code like '%" + textBox1.Text + "%'");

    this.MyListBox.ItemsSource = results;

    // Of course this not work
    Search1.Text = ""

}

private void turnVisibilityOn()
{
    // Inform the user updating the Search1 textblock
    // UIThread is a static class -Dispatcher.BeginInvoke(action)-
    UIThread.Invoke(() => Search1.Text = "Searching...");

}


public static class UIThread
{
   private static readonly Dispatcher Dispatcher;

       static UIThread()
       {
       // Store a reference to the current Dispatcher once per application
       Dispatcher = Deployment.Current.Dispatcher;
       }

       /// <summary>
       ///   Invokes the given action on the UI thread - if the current thread is the UI thread this will just invoke the action directly on
       ///   the current thread so it can be safely called without the calling method being aware of which thread it is on.
      /// </summary>
     public static void Invoke(Action action)
     {
         if (Dispatcher.CheckAccess())
         action.Invoke();
         else
         Dispatcher.BeginInvoke(action);
     }
}

1 个答案:

答案 0 :(得分:0)

我不确定我是否正确理解了这个问题。 “搜索...”文字没有出现?在

// Of course this not work
Search1.Text = ""

线不起作用? (你为什么写“当然这不行”?为什么它不起作用?)

我不明白为什么在后台线程中将文本更改为“正在搜索...”。你可以在UI线程中完成它,并在后台线程中进行耗时的工作,就像这样(我转而使用ThreadPool):

private void btnSearch_Tap( object sender, GestureEventArgs e )
{
    Search1.Text = "Searching..."

    ThreadPool.QueueUserWorkItem(p =>
    {
        Procedures[] results = CSDatabase.RunQuery<Procedures>( @"select Code, Description from tblLibraries where Description like '%" +
        textBox1.Text + "%' or Code like '%" + textBox1.Text + "%'" );

        // Dispatch manipulation of UI elements:
        Dispatcher.BeginInvoke( () =>
        {
            this.MyListBox.ItemsSource = results;
            Search1.Text = "";
        } );
    } ) ;
}

您始终必须从UI线程(运行事件处理程序)操作UI元素,并且您必须在后台线程中执行耗时的工作。