datgridview にデータバインドされた BindingList があります。リアルタイムの価格を追跡するために使用しています。メソッド「update(Quote quote)」は、さまざまなスレッドによって 1 秒間に複数回呼び出されます。datagridview に Quote が含まれていない場合は、追加されます。その場合、見積もりの値が更新されます。同じ引用符を BindingList (または GUI) に 2 回表示したくないので、値がリストにあるかどうかをチェックする操作をロックしようとしました。うまくいきません!私は何を間違っていますか?2 つの異なるロック方法を試しましたが、単なるオブジェクトではなく String オブジェクトをロックしています。問題は間違いなくBeginInvoke(new MethodInvoker(delegate() { activeQuotes.Insert(0, quote); }));
呼び出します (おそらく時間がかかります) が、その同期を行うと、「追加」メソッドは「クロススレッド」エラーをスローします。. . クロススレッドエラーを回避するにはどうすればよいですか?ただし、ロックも機能することを確認してください??
public BindingList<Quote> activeQuotes = new BindingList<Quote>();
object lockObject = "lockObject";
dataGridViewActive.DataSource = activeQuotes;
public void update(Quote quote)
{
//lock (lockObject)
if(Monitor.TryEnter(lockObject))
{
try
{
if (!activeQuotes.Contains(quote))
{
try
{
activeQuotes.Add(quote);
AddQuote(quote);
}
catch (Exception ex)
{
Console.WriteLine("Datagridview!!!!!!");
}
}
else
{
int index = activeQuotes.IndexOf(quote);
activeQuotes[index].Bid = quote.Bid;
activeQuotes[index].Ask = quote.Ask;
activeQuotes[index].Mid = quote.Mid;
activeQuotes[index].Spread = quote.Spread;
activeQuotes[index].Timestamp = quote.Timestamp;
}
finally
{
Monitor.Exit(lockObject);
}
}
private void AddQuote(Quote quote)
{
if (this.InvokeRequired)
{
BeginInvoke(new MethodInvoker(delegate() { activeQuotes.Insert(0, quote); }));
BeginInvoke(new MethodInvoker(delegate() { dataGridViewActive.Refresh(); }));
BeginInvoke(new MethodInvoker(delegate() { dataGridViewActive.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); }));
}
else
{
activeQuotes.Add(quote);
dataGridViewActive.Refresh();
dataGridViewActive.AutoResizeColumns (DataGridViewAutoSizeColumnsMode.AllCells);
}
}
これについて何か助けていただければ幸いです。
ありがとう。