BindingListを拡張し、アイテムの追加、削除時に「スレッド間操作インタフェースコントロール」異常が発生しないようにインタフェースを自動的に更新する
2015 ワード
コードの例 using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace TempForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Initial();
}
private UiBindList<int> _list;
private void Initial()
{
_list = new UiBindList<int> { SynchronizationContext = SynchronizationContext.Current };
bindingSource1.DataSource = _list;
new Thread(() =>
{
while (true)
{
Thread.Sleep(1000);
var newItem = DateTime.Now.Second;
_list.Add(newItem);
Thread.Sleep(1000);
_list.Remove(newItem);
}
})
{
IsBackground = true,
}
.Start();
}
}
/// <summary>
/// BindingList, 、 “ ”
/// </summary>
class UiBindList<T> : BindingList<T>
{
/// <summary>
///
/// </summary>
public SynchronizationContext SynchronizationContext { get; set; }
/// <summary>
///
/// </summary>
private void Excute(Action action, object state = null)
{
if (SynchronizationContext == null)
action();
else
SynchronizationContext.Post(d => action(), state);
}
public new void Add(T item)
{
Excute(() => base.Add(item));
}
public new void Remove(T item)
{
Excute(() => base.Remove(item));
}
}
}
ソースのダウンロード
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace TempForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Initial();
}
private UiBindList<int> _list;
private void Initial()
{
_list = new UiBindList<int> { SynchronizationContext = SynchronizationContext.Current };
bindingSource1.DataSource = _list;
new Thread(() =>
{
while (true)
{
Thread.Sleep(1000);
var newItem = DateTime.Now.Second;
_list.Add(newItem);
Thread.Sleep(1000);
_list.Remove(newItem);
}
})
{
IsBackground = true,
}
.Start();
}
}
/// <summary>
/// BindingList, 、 “ ”
/// </summary>
class UiBindList<T> : BindingList<T>
{
/// <summary>
///
/// </summary>
public SynchronizationContext SynchronizationContext { get; set; }
/// <summary>
///
/// </summary>
private void Excute(Action action, object state = null)
{
if (SynchronizationContext == null)
action();
else
SynchronizationContext.Post(d => action(), state);
}
public new void Add(T item)
{
Excute(() => base.Add(item));
}
public new void Remove(T item)
{
Excute(() => base.Remove(item));
}
}
}