代替锁使用Control.Invoke()(控制)Control、Invoke

由网友(咖啡加糖、甜到哀傷)分享简介:我的工作,需要为它的进展(一个DataGridView)来更新一个WinForms控件的多线程应用程序。为了prevent多次访问同一个共享资源,我开始了下面的锁结构:I am working on a multi-threaded application which needs to update a Winfor...

我的工作,需要为它的进展(一个DataGridView)来更新一个WinForms控件的多线程应用程序。为了prevent多次访问同一个共享资源,我开始了下面的锁结构:

I am working on a multi-threaded application which needs to update a Winforms control as it progresses (A DataGridView). In order to prevent multiple access to the same shared resource, I started out with the following lock structure:

if (DGV.Columns.Count >= DesiredColumnCount) return;
lock(DGV)
{
    while (DGV.Columns.Count < DesiredColumnCount)
    {
        DGV.Columns.Add(newColumn);
    }
}

我后来意识到,自从DGV是在UI线程上创建的,它需要 .Invoke()'D。这改变了code到:

I then realized that, since the DGV was created on the UI thread, it needs to be .Invoke()'d. This changes the code to:

if (DGV.Columns.Count >= DesiredColumnCount) return;
lock(DGV)
{
    DGV.Invoke(new MethodInvoker(() =>
        {
            while (DGV.Columns.Count < DesiredColumnCount)
            {
                DGV.Columns.Add(newColumn);
            }
        }
}

我的问题是:是不是这个多余的?在锁定将阻止辅助线程,直到它独占访问 DGV 调用()将阻止工作线程,直到UI线程可以拿起调用请求,并执行code。我不能只是得到只使用的invoke()

My question is: Isn't this redundant? the lock will block the worker thread until it has exclusive access to DGV, and the Invoke() will block the worker thread until the UI thread can pick up the invoke request and execute the code. Can't I just get by using only the Invoke()?

(这是最主要的问题。当然,如果有上述code任何其他多线程的罪,请评论)

(That is the main question. Of course if there are any other multithreading sins in the above code, please comment)

推荐答案

这是一个有点多余,在调用通话将派遣的operpation到UI线程。每个后续调用通话将派出以串行方式,所以也算不上什么需要做任何锁定。

It is a bit redundant, the Invoke call will "dispatch" the operpation to the UI thread. Each subsequent Invoke call will be dispatched in a serial fashion, so there isn't really any need to do any locking.

您可以考虑使用的BeginInvoke 而不是调用以prevent阻塞的工作线程,但再次,将要进行串联,所以没有必要担心锁定。

You may consider using BeginInvoke instead of Invoke order to prevent the worker thread from blocking, but again, that will be done "serially" so there is no need to worry about locking.

阅读全文

相关推荐

最新文章