同じニーズがあり、この助けに大いに感謝しています。これは少し変更されたバージョンです。
リストボックスを作成します。
<ListBox x:Name="lbLog" Background="LightGray"></ListBox>
メイン スレッド (コードの最初の部分) で、UI スレッドへの参照を格納するためにこれを配置します。
Thread m_UIThread;
....
m_UIThread = Thread.CurrentThread;
次に、これはログ メソッドであり、任意のスレッドから呼び出すことができます。
public void AddToLog(String message)
{
if (Thread.CurrentThread != m_UIThread)
{
// Need for invoke if called from a different thread
this.Dispatcher.BeginInvoke(
DispatcherPriority.Normal, (ThreadStart)delegate()
{
AddToLog(message);
});
}
else
{
// add this line at the top of the log
lbLog.Items.Insert(0, message);
// keep only a few lines in the log
while (lbLog.Items.Count > LOG_MAX_LINES)
{
lbLog.Items.RemoveAt(lbLog.Items.Count-1);
}
}
}