这里需要线程沟通吗?

时间:2015-12-28 09:51:21

标签: c# wpf multithreading xaml events

我试图让这段代码在一天的特定时间到达时向屏幕添加内容。它被操纵了一个事件。代码适用于单线程程序,但不适用于线程,这是我需要的。根据需要添加数据,但不会像在单线程执行时那样显示在屏幕上(timeStackStackPanelTimeEntry是{{} 1}})。

代码:

Mainwindow.xaml.cs

UserControl

SessionManager.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        SM = new SessionManager();
        SM.NewDayEvent += SplitSession;
        InitializeComponent();
        //Code removed for clarity
    }

    private void SplitSession(object sender, EventArgs ea)
    {
        SM.SplitSession();
        string s =((TimeEntry)SM.Entries.Last(x=>x.GetType()==typeof(TimeEntry))).Data.Comment;
        AddSessionStamp();
        entryAdder_Click(null, null);
        ((TimeEntry)SM.Entries.Last(x => x.GetType() == typeof(TimeEntry))).Data.Comment = s;
        this.Focus();
    }
    private void AddSessionStamp()
    {
        TextBlock timeStamp = new TextBlock();
        timeStamp.Text = "-----------" + SM.CurrentSession.Name + "-----------";
        timeStack.Children.Add(timeStamp);
    }
    private void entryAdder_Click(object sender, RoutedEventArgs e)
    {
        //Subscribe to the assorted events
        TimeEntry newTE = SM.addNewTimeEntry();
        //Subscribe to the assorted events
        RegisterToTimeEntry(newTE);
        timeStack.Children.Add(newTE);
    }
}

1 个答案:

答案 0 :(得分:2)

事件处理程序函数在与引发事件的人相同的线程中执行。问题是你无法从Dispatcher线程的另一个线程更新UI。您需要在Dispatcher Invoke或BeginInvoke中执行回调函数(或至少更新部分):

Application.Current.Dispatcher.Invoke(new Action(() => {
    //your UI update
}));