只执行一次代码块 [英] Preforming a block of code only once

查看:78
本文介绍了只执行一次代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码块,在 C# 中执行对象的加载.

The following code block, preforms loading of an object in C#.

public bool IsModelLoaded { get; set; }
public override MyObject Load()
    {
        if (!IsModelLoaded)
        {
            Model = MyService.LoadMyObject(Model);
            IsModelLoaded = true;
        }
        return Model;
    }

我的目的是只运行这个块一次,因此只加载一次模型.然而,这个代码块从 2 个不同的线程运行了两次..

My intention is to run this block only once, and hence loading the Model only once. Nevertheless, this code block runs twice from 2 different threads..

我怎样才能确保这个块只运行一次?(在多线程上).

How can I make sure that this block runs only once? (on multiplethreads).

谢谢.

推荐答案

最简单的就是添加

[MethodImpl(MethodImplOptions.Synchronized)]
public override MyObject Load()
{
   //snip
}

但请注意,这会锁定整个对象,而不仅仅是方法.不是很好的练习.

but be aware this puts a lock on the entire object, not just the method. Not really great practice.

http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx

同步

指定该方法一次只能由一个线程执行.静态方法锁定类型,而实例方法锁定实例.任何实例函数中只能执行一个线程,类的任何静态函数中只能执行一个线程.

Specifies that the method can be executed by only one thread at a time. Static methods lock on the type, whereas instance methods lock on the instance. Only one thread can execute in any of the instance functions, and only one thread can execute in any of a class's static functions.

这篇关于只执行一次代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆