Luckiest
Luckiest

Reputation: 3

How can i wrap a function in c# same as using inline header function in C

I am writing some class in c# that have a function

Print(string s)

In the last version i found out that this function called from many threads and every time this function called it should be locked. In C language i can rename this function to

PrintA(string s) 

and change the header file to something like

#define Print(a) {Lock(PrintA) //
                  { //
                      PrintA(a) //
                  } //
                 } 

Is it possible to write something like this in C#? I just want to change one place instead multiple place all over the code.

Upvotes: 0

Views: 138

Answers (2)

Eli Arbel
Eli Arbel

Reputation: 22739

There are no macros in C#. To add synchronization to a method, you can use:

void Print(string s)
{
    lock (lockObject) { PrintA(s); }
}

You'll need to define a lock object, simply add a field to your class

private readonly object lockObject = new object();

[MethodImpl(MethodImplOptions.Synchronized)] is less recommended as it uses this as the lock object, which means users can interfere with locking logic and cause deadlocks.

Upvotes: 2

Patryk Ćwiek
Patryk Ćwiek

Reputation: 14318

If you want to lock whole one method, you can decorate it with [MethodImpl(MethodImplOptions.Synchronized)] attribute:

[MethodImpl(MethodImplOptions.Synchronized)]
public void Print(string s)
{
    ...
}

For more specific control you'd have to use lock on a code block.

Upvotes: 0

Related Questions