Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 只是一个查询,关于主线程中的Invoke()_C#_Multithreading_Thread Safety_Invoke - Fatal编程技术网

C# 只是一个查询,关于主线程中的Invoke()

C# 只是一个查询,关于主线程中的Invoke(),c#,multithreading,thread-safety,invoke,C#,Multithreading,Thread Safety,Invoke,我有一个属性,可以在同一个类中使用Invoke()(来自线程)的方法和其他不使用Invoke()的方法修改它 如果他们在同一时刻被呼叫,会发生什么 这是可能的吗?因为可以通过某种方法影响条件 例如: public class Test{ public bool testBool { get; set; } public void MethodWIthInvoke(){ this.Invoke(new Action(() => {

我有一个属性,可以在同一个类中使用
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;
        }
    }
}

我不知道为什么你需要这样做的代码,反正,因为这两个方法将从同一个线程调用,那么它将是罚款。我想建议另一种编写代码的方法,如下所示:

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;
            }
        }
    }
}

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