【问题标题】:Just a enquiry, about Invoke() in Main thread只是一个查询,关于主线程中的 Invoke()
【发布时间】:2017-07-06 00:51:06
【问题描述】:

我有一个属性,可以从具有Invoke()(来自线程)的方法和其他没有invoke() 的方法在同一类中进行修改。

如果同时调用它们会发生什么?

这可能吗?因为可以通过某种方式影响条件。

例如:

public class Test{
    public bool testBool { get; set; }

    public void MethodWIthInvoke(){
        this.Invoke(new Action(() =>
        {
            if (testBool)
            {
                testBool = false;
            }
        }));
    }

    public void Method(){
        if (testBool)
        {
            testBool = false;
        }
    }
}

【问题讨论】:

  • 只要在 UI 线程中调用Method() 就可以了。
  • 是的,Method() 只是从 UI 线程调用,如果它们同时运行会发生什么?
  • @Cristian18 他们不能,如果他们都从同一个线程运行。它会做一个或另一个。
  • @Servy 很好,谢谢!
  • Test 类没有 Invoke() 方法,因此 sn-p 没有什么意义。如果这实际上是 Control.Invoke 或 Dispatcher.Invoke 调用,那么从 UI 线程进行调用并不重要。它可以看到您这样做,并将直接调度调用而不使用线程互操作管道。只有-5优雅点。不使用 Invoke() 返回值意味着您可以使用 BeginInvoke() 代替,-10 :)

标签: c# multithreading thread-safety invoke


【解决方案1】:

我不确定你为什么需要这样编写代码,因为这两个方法都会从同一个线程调用,所以没问题。我想建议另一种编写代码的方法,如下所示:

public class Test{
public bool testBool { get; set; }

 public void Method()
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new Action(() =>
            {
                if (testBool)
                {
                    testBool = false;
                }
            }));
        }
        else
        {
            if (testBool)
            {
                testBool = false;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多