如何在C#中由同一实例的另一方法锁定一个方法 [英] How to lock one method by another of same instance in c#

查看:138
本文介绍了如何在C#中由同一实例的另一方法锁定一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在名为ClassB的类中有两个方法,分别称为Method1和Method2,还有一个名为ClassA的类.
从classA开始:
1.创建一个ClassB实例,并且classB构造函数调用计时器(用于每10分钟调用一次MethodB)
2.创建一个线程,每10秒调用一次MethodA.

在MethodB正在更新时(通过计时器的调用),我需要锁定ClassB的MethodA.

由于MethodA和MethodB使用相同的静态变量.我想在那时从MethodB更新设置,所以我需要停止对MethodA进行处理.

这是我的代码:

I have a two methods say Method1 and Method2 in a class named ClassB and one more class called ClassA.

From classA Starts:
1.creates one instance of ClassB and classB constuctor invoke the timer(which used to call MethodB for every 10 mins )
2.creates thread to call MethodA for every 10 seconds.

while MethodB is updating (by the invocation of timer),i need to lock MethodA of ClassB.

Since MethodA and MethodB are using same static variables.I want to update settings from MethodB at that time i need to stop processing on MethodA.

Here is my code:

using System;
using System.Threading;

namespace ConsoleApplication1
{
    // ThreadLock.cs
    class ThreadLock
    {
        public static void DoLock()
        {
            Thread[] threads = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ParameterizedThreadStart(acc.DoTransactions));
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start(i+1);
                Thread.Sleep(1000);
            }
        }
    }

    class Account
    {
        private Object thisLock = new Object();
        private System.Threading.Timer updateBalanceThread = null;
        int balance;

        Random r = new Random();

        public Account(int initial)
        {
            balance = initial;

            //Update balance every 10 sec
            updateBalanceThread = new System.Threading.Timer(new TimerCallback(UpdateBalance), null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));

        }

        /// <summary>
        /// Update Balance
        /// Issue:During balance update,i need to wait withdrawal process after update only allow to withdraw
        /// </summary>
        /// &lt;param name="Balance"&gt;&lt;/param&gt;
        public void UpdateBalance(object Balance)
        {
            //when i update balance i need to stop withdrawal
            balance += 1000;
            Thread.Sleep(1000);
        }

        int Withdraw(int amount)
        {

            // This condition will never be true unless the lock statement
            // is commented out:
            if (balance &lt; 0)
            {
                throw new Exception("Negative Balance");
            }

            // Comment out the next line to see the effect of leaving out 
            // the lock keyword:
            lock (thisLock)
            {
              
                if (balance &gt;= amount)
                {
                    Console.WriteLine("Balance before Withdrawal :  " + balance);
                    Console.WriteLine("Amount to Withdraw        : -" + amount);
                    balance = balance - amount;
                    Console.WriteLine("Balance after Withdrawal  :  " + balance);
                    return amount;
                }
                else
                {
                    Console.WriteLine("Balance:" + balance + "---Withdrawal  :  " + amount);
                    return 0; // transaction rejected
                }
            }
        }

        public void DoTransactions(object threadNo)
        {
            //Need lock here

            Console.WriteLine("Threand Number:" + (string)threadNo.ToString());

            for (int i = 0; i &lt; 10; i++)
            {
                Withdraw(r.Next(1, 10));
            }          
        }
    }
}



有人可以解决我的问题吗?



Anyone solve my problem?

推荐答案

您可以使用全局静态变量isLocked为布尔值,初始化为false.

You can use a global static variable isLocked as boolean intialized as false.

Class B
{
    B()
    {
       while (!isLocked) {     
            isLocked = true
             MethodB()
            isLocked = false
       }
    }

}


您可以在从类A调用方法A的过程中使用类似的过程.这样可以防止methodA和MethodB同时被调用.


You can use similar procedure where you are calling Method A from Class A. This will prevent methodA and MethodB called simultaneously.


您不能仅在想要的部分周围使用lock(this)被锁定?当然,只要它们不从锁定部分相互调用即可.
Can''t you just use lock(this) around the parts you want to be locked? As long as they don''t call each other from within the locked part, of course.


如果您遇到静态成员问题,请为您的锁使用静态对象.

Use a static object for your lock if you are having problems with a static member.

private static staticLock = new Object();
...

lock(staticLock)
{
    //Access the static members...
}


这篇关于如何在C#中由同一实例的另一方法锁定一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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