blah blah blah is here! blah blah » Close

up1down
link

I need to make a API call, but I want to wrap the call in a (C#) lock.

What options do I have to wrap some logic in a lock to make it thread safe?

Is it possible to mark a particular class or method as serializable also?

last answered 2 years ago

1 answers

link

This is a typical pattern for locking some 'critical code' in C# so that it can only be accessed by one thread at a time.

class MyClass
{
static object padlock = new object();

public void SomeMethod()
{
lock(padlock)
{
// make API call
}
// other code (if any)
}

// other members
}

You can make the class binary serializable by decorating it with the [Serializable] attribute. However, it wouldn't make sense to apply this attribute to methods as it's the class's fields which are serializable, not local variables.

Feedback