I guess lock is for threading, but what do those two mean?
what other blocks of code are there in C# besides the unsafe{} block? :sick:
Printable View
I guess lock is for threading, but what do those two mean?
what other blocks of code are there in C# besides the unsafe{} block? :sick:
checked is used for arithmetic overflows
http://www.codeproject.com/csharp/overflow_checking.asp
there is a locked property which stops controls from being moved a design time, I don't know about a locked{} as a block.
lock {} creates a mutually exclusive lock on the code block within the brackets, whilst execution is within that block. Can be used to make a procedure/code block thread safe :)Quote:
Originally Posted by MrPolite
Example from MSDN:
Code:// statements_lock2.cs
using System;
using System.Threading;
class Account
{
int balance;
Random r = new Random();
public Account(int initial)
{
balance = initial;
}
int Withdraw(int amount)
{
// This condition will never be true unless the lock statement
// is commented out:
if (balance < 0)
{
throw new Exception("Negative Balance");
}
// Comment out the next line to see the effect of leaving out
// the lock keyword:
lock (this)
{
if (balance >= 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
{
return 0; // transaction rejected
}
}
}
public void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(1, 100));
}
}
}
class Test
{
public static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account (1000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
}
}
the lock{} blocks sounds cool, I dont really have much use for the check and unchecked block though
thanks for the replies :wave: