Semaphores and Lock in ASP MVC3 - asp.net-mvc-3

I am working with Asp.net MVC 3. Any reason why I cannot create a single instance of a thread process in MVC? I am trying to allow a single instance of a worker process one at a time. however it is allowing more than one instance at a time.
I followed the example at:
http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx
This is the code in my controller:
private static Semaphore _pool;
public ActionResult StartBots(int id)
{
_pool = new Semaphore(0, 1);
Thread t = new Thread(SingletonWorker);
t.Start();
_pool.Release(1);
return RedirectToAction("index", new { id = id });
}
I also tried this example using lock:
http://msdn.microsoft.com/en-us/library/c5kehkcz(v=VS.80).aspx
private Object thisLock = new Object();
public ActionResult StartBots(int id)
{
Thread t = new Thread(SingletonWorker);
lock (thisLock)
{
t.Start();
}
return RedirectToAction("index", new { id = id });
}
-------------------------------- Worker ------------------------------------
private static void SingletonWorker()
{
_pool.WaitOne(); <== this only applies to the Semaphore example.
// Do something here.
Thread.Sleep(rand.Next(4) * 200 + 1000);
// Do something else here.
}

Your code has several problems, but the most important one is - you only lock the Thread.Start, but that doesnt promise you'll have only one concurrent thread, it only means that only the thread creation is locked.
If what you want to force the threads to work serially, you could use the following code:
private static Object _lockKey = new Object();
public ActionResult SomeAction(int someParam)
{
ThreadPool.QueueUserWorkItem(doWork, SOME_STATE);
return SOMETHING;
}
private void doWork(object state)
{
lock (_lockKey)
{
/* Because of the static lockKey, this code will not be invoked serially */
}
}

Related

Mocking a class with internal SDK calls using NSubstitute

First time trying to use NSubstitute.
I have the following method in my Web API.
For those who don't know Couchbase, lets say that a collection/bucket is like a DB table and a key is like a DB row.
Couchbase_internal.Collection_GET returns Task<ICouchbaseCollection>
I would like to write 2 unit tests.
One that tests the returned class when the key exist and one when it doesn't (couchbaseServiceResultClass).
I don't really understand where is the part where I control whether or not the key exist in the mocked data.
public class CouchbaseAPI : ControllerBase, ICouchbaseAPI
{
// GET /document_GET?bucketName=<bucketName>&key=<key>
[HttpGet]
[Consumes("application/x-www-form-urlencoded")]
[Produces(MediaTypeNames.Application.Json)]
public async Task<couchbaseServiceResultClass> document_GET([FromQuery, BindRequired] string bucketName, [FromQuery, BindRequired] string key)
{
var collection = await Couchbase_internal.Collection_GET(bucketName);
if (collection != null)
{
IGetResult result;
try
{
// get document
result = await collection.GetAsync(key);
}
catch (CouchbaseException ex)
{
return new ErrorHandling().handleCouchbaseException(ex);
}
couchbaseServiceResultClass decryptResult = new();
try
{
// decrypt document
decryptResult = Encryption.decryptContent(result);
}
catch (Exception ex)
{
return new ErrorHandling().handleException(ex, null);
}
// remove document if decryption failed
if (!decryptResult.DecryptSuccess)
{
try
{
await collection.RemoveAsync(key);
}
catch (CouchbaseException ex)
{
return new ErrorHandling().handleCouchbaseException(ex);
}
}
decryptResult.Message = "key retrieved successfully";
// return result
return decryptResult;
}
else
{
return new ErrorHandling().handleError("Collection / bucket was not found.");
}
}
This is what I have so far for the first test:
public class CouchbaseAPITests
{
private readonly CouchbaseAPI.Controllers.ICouchbaseAPI myClass = Substitute.For<CouchbaseAPI.Controllers.ICouchbaseAPI>();
[Fact]
public async Task document_GET_aKeyIsRetrievedSuccessfully()
{
// Arrange
string bucketName = "myBucket";
string keyName = "myKey";
couchbaseServiceResultClass resultClass = new();
resultClass.Success = true;
resultClass.Message = "key retrieved successfully";
myClass.document_GET(bucketName, keyName).Returns(resultClass);
// Act
var document = await myClass.document_GET(bucketName, keyName);
// Assert
Assert.True(document.Success);
Assert.Equal("key retrieved successfully", document.Message);
}
}
If we want to test that we are retrieving documents from the Couchbase API properly, then generally we want to use a real instance (local test setup) of that API where possible. If we are mocking this then our tests are not really telling us about whether our code is working correctly (just that our mock is working the way we want it to).
When certain APIs are difficult to use real instances for (e.g. non-deterministic code, difficult to reproduce conditions such as network errors, slow dependencies, etc), that's when it can be useful to introduce an interface for that dependency and to mock that for our test.
Here's a very rough example that doesn't quite match the code snippets posted, but hopefully will give you some ideas on how to proceed.
public interface IDataAdapter {
IEnumerable<IGetResult> Get(string key);
}
public class CouchbaseAdapter : IDataAdapter {
/* Implement interface for Couchbase */
}
public class AppApi {
private IDataAdapter data;
public AppApi(IDataAdapter data) {
this.data = data;
}
public SomeResult Lookup(string key) {
try {
var result = data.Get(key);
return Transform(Decrypt(result));
} catch (Exception ex) { /* error handling */ }
}
}
[Fact]
public void TestWhenKeyExists() {
var testAdapter = Substitute.For<IDataAdapter>();
var api = new AppApi(testAdapter);
testAdapter.Get("abc").Returns(/* some valid data */);
var result = api.Lookup("abc");
/* assert that result is decrypted/transformed as expected */
Assert.Equal(expectedResult, result);
}
[Fact]
public void TestWhenKeyDoesNotExist() {
var testAdapter = Substitute.For<IDataAdapter>();
var api = new AppApi(testAdapter);
var emptyData = new List<IGetResult>();
testAdapter.Get("abc").Returns(emptyData);
var result = api.Lookup("abc");
/* assert that result has handled error as expected */
Assert.Equal(expectedError, result);
}
Here we've introduced a IDataAdapter type that our class uses to abstract the details of which implementation we are using to get data. Our real code can use the CouchbaseAdapter implementation, but our tests can use a mocked version instead. For our tests, we can simulate what happens when the data adapter throws errors or returns specific information.
Note that we're only testing AppApi here -- we are not testing the CouchbaseAdapter implementation, only that AppApi will respond in a certain way if its IDataAdapter has certain behaviour. To test our CouchbaseAdapter we will want to use a real instance, but we don't have to worry about those details for testing our AppApi transformation and decryption code.

Xamarin Realm - when to close Realm

I have a Shared Project where I have changed the database to Realm instead of SQLite.
My problem is, if I close the Realm in my DatabaseManager, the result is removed. Therefore i have created a static singelton instance of the Realm, which all my DatabaseManager use. Now my app crash after short time on memory, and if i remove all my database-functions, it works.
I create my Realm-instance here:
public class RealmDatabase
{
private Realm mRealmDB;
public Realm RealmDB
{
get
{
if (mRealmDB == null || mRealmDB.IsClosed)
{
SetRealm ();
}
return mRealmDB;
}
}
static RealmDatabase cCurrentInstance;
public static RealmDatabase Current
{
get
{
if (cCurrentInstance == null)
cCurrentInstance = new RealmDatabase ();
return cCurrentInstance;
}
}
public RealmDatabase ()
{
}
private void SetRealm ()
{
var config = new RealmConfiguration ("DBName.realm", true);
mRealmDB = Realm.GetInstance (config);
}
public Transaction BeginTransaction ()
{
return RealmDB.BeginWrite ();
}
}
The I have my DatabaseManagler looking like this:
public class NewFreeUserManager
{
internal Realm RealmDB = RealmDatabase.Current.RealmDB;
static NewFreeUserManager cCurrentInstance;
public static NewFreeUserManager Current
{
get
{
if (cCurrentInstance == null)
cCurrentInstance = new NewFreeUserManager ();
return cCurrentInstance;
}
}
private NewFreeUserManager ()
{
}
internal bool Save (FreeUser freeuser)
{
try
{
using (var trans = RealmDB.BeginWrite ())
{
RealmDB.RemoveAll<FreeUser> ();
var fu = RealmDB.CreateObject<FreeUser> ();
fu = freeuser;
trans.Commit ();
}
return true;
}
catch (Exception e)
{
Console.WriteLine ("FreeUser save: " + e.ToString ());
return false;
}
}
internal FreeUser Get ()
{
return RealmDB.All<FreeUser> ().FirstOrDefault ();
}
}
Can anyone help me?
there are a few issues with your current setup that prevent you from persisting objects properly.
The first and very important one is that Realm instances are not thread-safe. That is, using them as singletons is strongly discouraged, unless you are certain that you'll never access them from another thread.
The second is more subtle, but in your save method you are calling:
var fu = RealmDB.CreateObject<FreeUser>();
fu = freeuser;
What it does is, effectively, you are creating an object in the Realm, and then assigning the variable to another object. This will not assign freeuser's properties to fu, it just replaces one reference with another. What you're looking for is Realm.Manage so your code should look like this:
using (var trans = RealmDB.BeginWrite())
{
RealmDB.Manage(freeuser);
trans.Commit();
}
Once you fix the second bug, you should be able to go back and close Realm instances when you don't need them anymore.

Cancelling task from taskschedule cancels all other tasks in it

First of all, i'm really new to multithreading and to tpl in particular, so the code below could be bad. Really bad:)
So, I have following objective:
There is task queue, tasks proceeds inline, and progress of task "working" should be on the ProgressBar.
I was overloaded TaskScheduler class:
public class MyTaskScheduler:TaskScheduler
{
[ThreadStatic]
private static bool _currentThreadIsProcessingItems;
private static Logger _logger;
private readonly TaskQueue _scheduledTasks;
private readonly int _maxDegreeOfParallelism;
private int _delegatesQueuedOrRunning = 0;
public MyTaskScheduler(int maxDegreeOfParallelism)
{
_logger = LogManager.GetLogger("log");
_maxDegreeOfParallelism = maxDegreeOfParallelism;
_scheduledTasks = new TaskQueue();
}
public override int MaximumConcurrencyLevel { get { return 1; } }
protected override IEnumerable<Task> GetScheduledTasks()
{
lock (_scheduledTasks)
{
return _scheduledTasks.ToList();
}
}
protected override void QueueTask(Task task)
{
lock (_scheduledTasks)
{
_scheduledTasks.Enqueue(task);
if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism)
{
++_delegatesQueuedOrRunning;
NotifyThreadPoolOfPendingWork();
}
}
_logger.Info("Task queued");
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (!_currentThreadIsProcessingItems) return false;
if (taskWasPreviouslyQueued)
if (TryDequeue(task))
return TryExecuteTask(task);
else
return false;
return TryExecuteTask(task);
}
private void NotifyThreadPoolOfPendingWork()
{
ThreadPool.UnsafeQueueUserWorkItem(_ =>
{
_currentThreadIsProcessingItems = true;
try
{
while (true)
{
Task item;
lock (_scheduledTasks)
{
if (_scheduledTasks.Count == 0)
{
--_delegatesQueuedOrRunning;
break;
}
item = _scheduledTasks.Dequeue();
}
_logger.Info("Execution of thread with id {0} started",item.Id);
TryExecuteTask(item);
_logger.Info("Execution of thread with id {0} ended", item.Id);
MessageBox.Show("ggg");
}
}
finally
{
_currentThreadIsProcessingItems = false;
}
}
, null);
}
}
And there is the part of code I initialize my queue:
private readonly List<Task> _tasks = new List<Task>();
readonly CancellationTokenSource _cts = new CancellationTokenSource();
private MyTaskScheduler _scheduler;
readonly TaskFactory _factory;
private int _currentNumberOfThreads;
public Form1(bool isMainForm)
{
InitializeComponent();
_logger = LogManager.GetLogger("log");
_isMainForm = isMainForm;
_currentNumberOfThreads = 0;
_scheduler = new MyTaskScheduler(1);
_factory = new TaskFactory(_scheduler);
if (_isMainForm == false)
{
_currentNumberOfThreads++;
var t = _factory.StartNew(() => DoWork(_cts.Token), _cts.Token);
_tasks.Add(t);
}
It works perfectly until i try to cancel current task.
private void button2_Click(object sender, EventArgs e)
{
_logger.Info("Initialized cancelling of current thread");
_cts.Cancel();
_currentNumberOfThreads--;
}
This canceling not only current task, but all tasks in queue as i can see from logs:
01:56:18 Task queued
01:56:18 Execution of thread with id 1 started
01:56:18 Thread's DoWork() begun
01:56:19 Task queued
01:56:22 Task queued
01:56:30 Thread {0} DoWork() ended
01:56:30 Execution of thread with id 1 ended
01:56:31 Execution of thread with id 2 started
01:56:31 Thread's DoWork() begun
01:56:32 Task queued
01:56:32 Task queued
01:56:33 Task queued
01:56:34 Initialized cancelling of current thread
01:56:34 Execution of thread with id 2 ended
01:56:35 Execution of thread with id 3 started
01:56:35 Execution of thread with id 3 ended
01:56:36 Execution of thread with id 4 started
01:56:36 Execution of thread with id 4 ended
01:56:36 Execution of thread with id 5 started
01:56:36 Execution of thread with id 5 ended
01:56:37 Execution of thread with id 6 started
01:56:37 Execution of thread with id 6 ended
Task cancellation should cancel only current task and next task in queue should start and work as usual.
I'm really confused and don't know what am I doing wrong. I have an idea that CancellationTokenSource I used to cancel my task, refers to the whole schedule, not to concrete task, but I can't prove it myself. So any help will be appreciated.
P.S. Sorry for my bad English.
It's actually pretty simple:
you are using one single cancellation token as a field.
readonly CancellationTokenSource _cts = new CancellationTokenSource();
If you want to cancel only one single task, you need to create one token per task, and only cancel the one passed to the task you want to abort. simple as that :)

How can I await modal form dismissal using Xamarin.Forms?

Using Xamarin.Forms how can I use make an async method that waits for the form to dismiss? If I use
await Navigation.PushModalAsync(page);
it will return once the animation is finished not when the page is dismissed.
I want a to create modal Task SignInAsync method that return true if sign-in is successful.
You can do this by triggering an event in your login page and listen for that event before going on, but you want the full TAP support and I second you there. Here's a simple yet working 2 page app that does just this. You'll obviously want to use ContentPage custom subclass and have proper methods instead of my quick Commands, but you get the idea, and it saves me typing.
public static Page GetFormsApp ()
{
NavigationPage navpage = null;
return navpage = new NavigationPage (new ContentPage {
Content = new Button {
Text = "Show Login dialog",
Command = new Command (async o => {
Debug.WriteLine ("Showing sign in dialog");
var result = await SignInAsync (navpage);
Debug.WriteLine (result);
})
}
});
}
static Task<bool> SignInAsync (NavigationPage navpage)
{
Random rnd = new Random ();
var tcs = new TaskCompletionSource<bool> ();
navpage.Navigation.PushModalAsync (new ContentPage {
Content = new Button {
Text = "Try login",
Command = new Command ( o => {
var result = rnd.Next (2) == 1;
navpage.Navigation.PopModalAsync ();
tcs.SetResult (result);
})
}
});
return tcs.Task;
}
The minor drawback is that the Task<bool> returns before the end of the pop modal animation, but that's:
easy to fix
only an issue if you're awaiting that result to push a new modal Page. Otherwise, meh, just go on.
Override OnAppearing
Firstly, it's worth noting that simply overriding OnAppearing in the calling Page may suffice in many circumstances.
protected override void OnAppearing()
{
base.OnAppearing();
...
// Handle any change here from returning from a Pushed Page
}
(note that the pushed page's OnDisappearing override is called after the caller's OnAppearing - seems a bit backwards to me!)
AwaitableContentPage
Secondly...this is my take on #Chad Bonthuys answer:
public class AwaitableContentPage : ContentPage
{
// Use this to wait on the page to be finished with/closed/dismissed
public Task PageClosedTask { get { return tcs.Task; } }
private TaskCompletionSource<bool> tcs { get; set; }
public AwaitableContentPage()
{
tcs = new System.Threading.Tasks.TaskCompletionSource<bool>();
}
// Either override OnDisappearing
protected override void OnDisappearing()
{
base.OnDisappearing();
tcs.SetResult(true);
}
// Or provide your own PopAsync function so that when you decide to leave the page explicitly the TaskCompletion is triggered
public async Task PopAwaitableAsync()
{
await Navigation.PopAsync();
tcs.SetResult(true);
}
}
And then call it thus:
SettingsPage sp = new SettingsPage();
await Navigation.PushAsync(sp);
await sp.PageClosedTask; // Wait here until the SettingsPage is dismissed
Just thought I would contribute to this one, although it's been a while since it was asked and answered. I built upon the answer by #noelicus. I wanted a generic way to do this with multiple situations so the Task needs to be able to return not just bool but anything. Then, using generics:
public class AwaitableContentPage<T> : ContentPage
{
// Use this to wait on the page to be finished with/closed/dismissed
public Task<T> PageClosedTask => tcs.Task;
// Children classes should simply set this to the value being returned and pop async()
protected T PageResult { get; set; }
private TaskCompletionSource<T> tcs { get; set; }
public AwaitableContentPage()
{
tcs = new TaskCompletionSource<T>();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
tcs.SetResult(PageResult);
}
}
Now, in the page you want to run as modal, you can do:
public partial class NewPerson : AwaitableContentPage<Person>
and when done, simply do:
base.PageResult = newPerson; // object you created previously
await base.Navigation.PopAsync();
Then, to make it super simple to use, use an extension method:
public static class ExtensionMethods
{
async public static Task<T> GetResultFromModalPage<T>(this INavigation nav, AwaitableContentPage<T> page)
{
await nav.PushAsync(page);
return await page.PageClosedTask;
}
That's all. Now, in your code, in any page where you want to use this, the syntax ends up simply like this:
Person newPerson = await Navigation.GetResultFromModalPage<string>(new NewPersonCreatePage());
if (newPerson != null)
UseNewPersonCreatedByOtherPage();
Hope this helps!
In my implementation I used:
await navigation.PopModalAsync();
Full Example:
private INavigation navigation;
public LoginPageModel(INavigation navigation, LoginPage loginPage)
{
this.navigation = navigation;
this.loginPage = loginPage;
}
public bool IsValid { get; set; }
protected async void ExecuteLoginCommand()
{
var loginResult = await AuthenticationHelper.Authenticate(Email, Password);
var isValid = false;
if (loginResult != null)
{
isValid = true;
}
//return isValid;
AuthenticationResult(isValid);
}
private async void AuthenticationResult(bool isValid)
{
if (isValid)
{
Debug.WriteLine("Logged in");
await navigation.PopModalAsync();
}
else
{
Debug.WriteLine("Failed" + email + password);
await loginPage.DisplayAlert("Authentication Failed", "Incorrect email and password combination","Ok", null);
}
}
The answer selected and given by #Stephane Delcroix above is awesome. But for anybody willing to push this further, by waiting for a page's completion and returning more structured data in a good MVVM fashion, you could do the following:
By calling an event from the page's OnDisapearing method, this event can then be subscribed by the navigation service which you create, and you can then use the "TaskCompletionSource" to wati until your page finishes its work and then complete the task.
For more details about accomplishing this, you can check this blog post.
Here is the base page's implementation, every page in this demo app inherit this page:
public class BasePage<T> : ContentPage
{
public event Action<T> PageDisapearing;
protected T _navigationResut;
public BasePage()
{
}
protected override void OnDisappearing()
{
PageDisapearing?.Invoke(_navigationResut);
if (PageDisapearing != null)
{
foreach (var #delegate in PageDisapearing.GetInvocationList())
{
PageDisapearing -= #delegate as Action<T>;
}
}
base.OnDisappearing();
}
}
Here is an overview of the navigation service you should use:
public async Task<T> NavigateToModal<T>(string modalName)
{
var source = new TaskCompletionSource<T>();
if (modalName == nameof(NewItemPage))
{
var page = new NewItemPage();
page.PageDisapearing += (result) =>
{
var res = (T)Convert.ChangeType(result, typeof(T));
source.SetResult(res);
};
await App.Current.MainPage.Navigation.PushModalAsync(new NavigationPage(page));
}
return await source.Task;
}
To call this page with the navigation service, you can use the following code:
var item = await new SimpleNavigationService().NavigateToModal<Item>(nameof(NewItemPage));
Items.Add(item);

Distributed Lock Service with Windows Server AppFabric Caching

I have an extension method for the Microsoft.ApplicationServer.Caching.DataCache object found in the Windows Server AppFabric SDK that looks like this:
using System;
using System.Collections.Generic;
using Microsoft.ApplicationServer.Caching;
namespace Caching
{
public static class CacheExtensions
{
private static Dictionary<string, object> locks = new Dictionary<string, object>();
public static T Fetch<T>(this DataCache #this, string key, Func<T> func)
{
return #this.Fetch(key, func, TimeSpan.FromSeconds(30));
}
public static T Fetch<T>(this DataCache #this, string key, Func<T> func, TimeSpan timeout)
{
var result = #this.Get(key);
if (result == null)
{
lock (GetLock(key))
{
result = #this.Get(key);
if (result == null)
{
result = func();
if (result != null)
{
#this.Put(key, result, timeout);
}
}
}
}
return (T)result;
}
private static object GetLock(string key)
{
object #lock = null;
if (!locks.TryGetValue(key, out #lock))
{
lock (locks)
{
if (!locks.TryGetValue(key, out #lock))
{
#lock = new object();
locks.Add(key, #lock);
}
}
}
return #lock;
}
}
}
The intent is to let the developer write code that says, "fetch me some data by trying the cache first. if it's not available in cache execute the specified function, put the results in cache for the next caller, then return the results". Like this:
var data = dataCache.Fetch("key", () => SomeLongRunningOperation());
The locking limits executing the potentially long running function call to a single thread but only within a single process on the same machine. How would you expand on this pattern to make the locking distributed to prevent multiple processes/machines from executing the function at once?
AppFabric has it's own distributed locking mechanism which you can access through the GetAndLock/PutAndUnlock family of methods. If your item is locked, a normal Get call will still succeed and return the last value, but further GetAndLock calls will throw an Exception. In the case where your client is requesting a cached object for the first time, you can still lock the key even though it doesn't really exist yet (it's kind of more like a reservation than a solid lock).
public static T Fetch<T>(this DataCache #this, string key, Func<T> func, TimeSpan timeout)
{
var result = #this.Get(key);
if (result == null)
(
DataCacheLockHandle handle;
// We need a timespan to allow func time to run
TimeSpan funcTimespan = New TimeSpan(0,1,0);
try
{
// Lock the key
// If something goes wrong here it will unlock at the end of funcTimespan
var result = #this.GetAndLock(key, funcTimespan, handle);
if (result == null)
{
// Still no value so go and run func
result = func();
#this.PutAndUnlock(key, result, handle, timeout);
}
else
{
// There's a value now so we'll unlock the key and reset it's timeout
#this.Unlock(key, handle, timeout);
}
}
catch (DataCacheException ex)
{
if (ex.ErrorCode == DataCacheErrorCode.ObjectLocked)
{
// Another process has locked the key so func must be running right now
// We'll return null to the client
result = null;
}
}
if (result == null)
{
return null;
}
else
{
return (T)result;
}
)
}
I was looking for a good implementation of this and came up with my own:
Distributed Lock with AppFabric Caching
Essentially it's an AcquireLock() extension method to the DataCache class which you can use like this:
DataCache cache = factory.GetCache("MyCache");
using (cache.AcquireLock("MyLock"))
{
// Lock acquired, perform synchronized work here
}

Resources