Instance Variable - c#

Please consider code below. Each time I run the code, output will be always 0 and 3. I am sure it has something to do with single instance but didn't have any explanation why this is happening. It will be great if you can help me understand this. Thank you for your help.
Is this happening because variable points to a different location in heap each time we initialize it ?
public class Helper
{
List<int> list = new List<int>();
public List<int> GetList
{
get
{
return list;
}
}
public async Task<bool> Process()
{
await Task.Delay(1);
//sleep this thread for 6 seconds
Thread.Sleep(6000);
//When I debug, both of the thread adds into the list
//but first thread always have zero element on this list, if it adds to the list then where it is getting lost ?
//not sure why ? Has to do something with the variable below _confighelper
//but why it behaves likes this ? what would be the best explanation?
//where this variable is getting lost ?
list.Add(1);
list.Add(2);
list.Add(3);
return true;
}
}
public class RunOp
{
//Has to do something with single instance
Helper _configHelper;
public async Task Run()
{
_configHelper = new Helper();
var val = await _configHelper.Process();
Console.WriteLine(_configHelper.GetList.Count);
}
}
class Program
{
static void Main(string[] args)
{
RunOp op = new RunOp();
Task.Factory.StartNew(async () =>
{
await op.Run();
});
Thread.Sleep(4000);
//Start another thread after 4 seconds
Task.Factory.StartNew(async () =>
{
await op.Run();
});
Console.ReadLine();
}
}

This is a simple case of thread safety, and this is not thread safe
The problem is RunOp has an internal Helper, which gets overwritten and showing (what seems) inconsistent results because of the thread sleeps and delays.
Here is a thread safe version
public class RunOp
{
private SemaphoreSlim slim = new SemaphoreSlim(1,1);
//Has to do something with single instance
Helper _configHelper;
public async Task Run()
{
await slim.WaitAsync();
_configHelper = new Helper();
var val = await _configHelper.Process();
Console.WriteLine(_configHelper.GetList.Count);
slim.Release();
}
// or
public async Task Run()
{
Helper configHelper = new Helper();
var val = await configHelper.Process();
Console.WriteLine(configHelper.GetList.Count);
}
}
I know this is only an academic problem, but this really should be refactored and thought through again

Related

Strange case involving TaskContinuationOptions.RunContinuationsAsynchronously

async void Main()
{
T0.TT();
}
private class T0
{
[ThreadStatic] private static int test;
public static async void TT()
{
test = 4;
var continuation = new System.Threading.Tasks.TaskCompletionSource<int>(System.Threading.Tasks.TaskContinuationOptions.RunContinuationsAsynchronously);
var th = new Thread(() => { Thread.Sleep(500); Console.WriteLine(test); test = 3; continuation.TrySetResult(5); test = 7; });
th.Start();
Console.WriteLine(await continuation.Task);
Console.WriteLine(test);
}
}
Output:
0
5
3
So without the System.Threading.Tasks.TaskContinuationOptions.RunContinuationsAsynchronously this was written to demonstrate the rest of the async method runs on the thread created by new Thread(). However with System.Threading.Tasks.TaskContinuationOptions.RunContinuationsAsynchronously it still somehow finds that specific [ThreadStatic] value that is set in the newly created thread (thus can't be a TaskScheduler thread) and cleared as soon as TrySetResult returns.
What the hey? How is this happening?
You should be passing TaskCreationOptions.RunContinuationsAsynchronously, not TaskContinuationOptions.RunContinuationsAsynchronously.
Passing TaskContinuationOptions.RunContinuationsAsynchronously will call the overload that takes an object parameter, treating it as a "state" object and not as a flag controlling the TCS behavior.

How to access to Task argument?

Suppose I have a List<Task>:
private readonly List<Task> _tasks = new List<Task>(new Task[9]);
I want create a Task for start the DoWorkAsync method available inside the class Foo, so what I did is the following:
_tasks[0] = new Task<Foo>(() => new Foo().DoWorkAsync());
so the Foo class contains DoWorkAsync method which have a design similar to this:
public async Task HeavyAsync()
{
while (true)
{
string newData = DateTime.Now.ToLongTimeString();
Console.WriteLine(newData);
await Task.Delay(200);
}
}
actually I can start the Task using _tasks[0].Start();.
This works, but the main problem is that I want access to the public property of Foo class and I can't, because when I type this: _tasks[0].
I'll get the following method:
I also tried using GetAwaiter() and await:
var foo = await _tasks[0];
but I'll get the following error:
Cannot assign void to an implicitly-typed local variable
How can I access to the Foo properties?
You have to change the interface of your method. A task is just a "function pointer" that is executed and then finished. If you need the object, that contains the executed function, then you have to save or return it somewhere.
I would do the following: change the async method to return an object like:
public async Task<Foo> HeavyAsync()
{
while (true)
{
string newData = DateTime.Now.ToLongTimeString();
Console.WriteLine(newData);
await Task.Delay(200);
}
return this;
}
then this statement
var foo = await _tasks[0];
should give you with foo a reference to your Foo-object.
UPDATE:
Or you give your class Foo the following property and methods:
class Foo
{
private Task runningTask {get;set;}
public void StartTask()
{
runningTask = Task.Start( () => ....);
}
public async Task WaitTask()
{
await runningTask;
}
public bool IsRunning => runningTask != null && runningTask.Status......
And instead of holding a list of Task in your calling method, you might hold the list of Foo instances.

What is the best way to make a time measuring wrapper class for functions?

I want to start measuring the time it took for a function to run in my program in multiple locations.
Dealing with the StopWatch seemed a bit messy in the code so i decided to wrap it.
These are the things I need:
the function will receive an async function that may or may not have a return value
i need to get out of the function two things: the return value if it exists and the time in seconds it took for it to run
I want to find a readable and sustainable solution since it will be used in multiple projects.
this is what i did so far:
public class TimeMeasurer
{
private readonly Stopwatch _stopWatch;
public TimeMeasurer()
{
_stopWatch = new Stopwatch();
}
public async Task<Tuple<double, TReturn>> Start<TReturn>(Func<Task<TReturn>> function)
{
try
{
_stopWatch.Start();
var val = await function();
var took = _stopWatch.Elapsed.TotalSeconds;
return Tuple.Create(took, val);
}
finally
{
_stopWatch.Stop();
_stopWatch.Reset();
}
}
public async Task<double> Start(Func<Task> function)
{
try
{
_stopWatch.Start();
await function();
var took = _stopWatch.Elapsed.TotalSeconds;
return took;
}
finally
{
_stopWatch.Stop();
_stopWatch.Reset();
}
}
}
if there isnt a better solution..
Is there a way to merge between the two functions? (one to include a return value and the second to get void functions)
Is there a way to return something clearer than tuple? I find it kind of messy to deal with
edit: calling the class i made also doesnt look good..
var tuple = await _timeMeasurer.Start(async () => await function(param1, param2));
EDIT: I decided to give this idea up. Its too messy. In the end im using StopWatch
For your first point, there is not much more you could do that could combine the functions, there is just not much logic to combine.
For your second point I would make two custom classes to hold the result. You could get fancy and do some inheritance too and return the entire task object instead of just the result in case someone wanted to look at some of the properties of the returned task.
Lastly there is no reason your function should be a instance, the entire class could be made static.
Here is a example that has the changes I suggested.
public class TimeMeasurerResult
{
protected readonly Task _task;
private readonly TimeSpan _duration;
public TimeMeasurerResult(Task task, TimeSpan duration)
{
_task = task;
_duration = duration;
}
public Task Task {get { return _task;}}
public TimeSpan Duration {get {return _duration;}}
}
public class TimeMeasurerResult<T> : TimeMeasurerResult
{
public TimeMeasurerResult(Task<T> task, TimeSpan duration)
:base(task, duration)
{
}
public T Result {get { return ((Task<T>)_task).Result;}}
}
public static class TimeMeasurer
{
public static async Task<TimeMeasurerResult<TReturn>> Start<TReturn>(Func<Task<TReturn>> function)
{
var stopWatch = Stopwatch.StartNew();
var task = function();
await task;
var took = stopWatch.Elapsed;
return new TimeMeasurerResult<TReturn>(task, took);
}
public static async Task<TimeMeasurerResult> Start(Func<Task> function)
{
var stopWatch = Stopwatch.StartNew();
var task = function();
await task;
var took = stopWatch.Elapsed;
return new TimeMeasurerResult(task, took);
}
}
Here is a example of using it, note that I only needed to do var results = await TimeMeasurer.Start(() => Function(a,b)); not var results = await TimeMeasurer.Start(async () => await Function(a,b));
public class Program
{
public static void Main()
{
AsyncMain().Wait();
}
public static async Task AsyncMain()
{
int a = 500;
int b = 10;
var results = await TimeMeasurer.Start(() => Function(a,b));
Console.WriteLine("Waited: {0}", results.Duration.TotalSeconds);
Console.WriteLine("Result: {0}", results.Result);
}
public static async Task<int> Function(int a, int b)
{
var total = a + b;
await Task.Delay(total);
return total;
}
}

Chaining locks?

When trying to answer the following question, I wrote this piece of code :
using static MyNameSpace.Locker; //So that we don't need to specify the static class name before each call.
public class MainClass
{
public MainMethod()
{
Lock(new object()).Lock(new object()).RunAction(() => Console.WriteLine("Finished"));
}
}
public static class Locker
{
public static async Task<List<object>> Lock(object toLock, int timeout = -1)
{
await Task.Run(() => TryEnter(toLock, timeout));
return new List<object>() { toLock };
}
public static async Task<List<object>> Lock(
this Task<List<object>> lockedChain,
object toLock,
int timeout = -1)
{
await Task.Run(() => TryEnter(toLock, timeout));
await lockedChain;
lockedChain.Result.Add(toLock)
return lockedChain.Result;
}
public static async void RunAction(this Task<List<object>> lockChain, Action toRun)
{
await lockChain;
try
{
toRun.Invoke();
}
finally
{
foreach (var chainMember in lockChain.Result)
{
Monitor.Exit(chainMember);
}
}
}
private static void TryEnter(object toLock, int timeout = -1)
{
var success = false;
if (timeout > 0)
{
success = Monitor.TryEnter(toLock, timeout);
}
else
{
success = Monitor.TryEnter(toLock);
}
if (!success)
{
throw new TimeoutException();
}
}
}
But as some user rightfully remarked, this won't work for a very simple reason : Since the methods are async, they may not run on the same thread, thus throwing an exception when trying to release the Monitor.
How would one go to ensure the Enter and Exit method of the monitor a run on the same thread ?
Instead of forcing the lock operations onto the same thread which is nearly impossible, use a lock that is not thread-affine: SemaphoreSlim. It has native async support as well (as opposed to blocking).
In the original question that you linked to I'd go with this answer instead. Seems cleaner than the chain solution which contains a lot of artificial complexity. Code quality is not so much about the specific call syntax being used. Just by putting things in a syntactic chain you cannot reduce complexity much.
In particular the chain solution is just a complicated way of saying Lock(new [] { lock1, lock2 }, () => ...); I think. All the chain does it build up a list. using makes this even simpler because it does away with the lambda. Lambdas are less composable because you can't return from the lambda like you can from using. I think you should target this:
using (MultiLock(new [] { lock1, lock2 }, timeout)) {
//...
}

Asynchronous programming design pattern

I'm working on a little technical framework for CF.NET and my question is, how should I code the asynchronous part? Read many things on MSDN but isn't clear for me.
So, here is the code :
public class A
{
public IAsyncResult BeginExecute(AsyncCallback callback)
{
// What should I put here ?
}
public void EndExecute()
{
// What should I put here ?
}
public void Execute()
{
Thread.Sleep(1000 * 10);
}
}
If someone can help me...
Thanks !
You could use a delegate:
public class A
{
public void Execute()
{
Thread.Sleep(1000 * 3);
}
}
class Program
{
static void Main()
{
var a = new A();
Action del = (() => a.Execute());
var result = del.BeginInvoke(state =>
{
((Action)state.AsyncState).EndInvoke(state);
Console.WriteLine("finished");
}, del);
Console.ReadLine();
}
}
UPDATE:
As requested in the comments section here's a sample implementation:
public class A
{
private Action _delegate;
private AutoResetEvent _asyncActiveEvent;
public IAsyncResult BeginExecute(AsyncCallback callback, object state)
{
_delegate = () => Execute();
if (_asyncActiveEvent == null)
{
bool flag = false;
try
{
Monitor.Enter(this, ref flag);
if (_asyncActiveEvent == null)
{
_asyncActiveEvent = new AutoResetEvent(true);
}
}
finally
{
if (flag)
{
Monitor.Exit(this);
}
}
}
_asyncActiveEvent.WaitOne();
return _delegate.BeginInvoke(callback, state);
}
public void EndExecute(IAsyncResult result)
{
try
{
_delegate.EndInvoke(result);
}
finally
{
_delegate = null;
_asyncActiveEvent.Set();
}
}
private void Execute()
{
Thread.Sleep(1000 * 3);
}
}
class Program
{
static void Main()
{
A a = new A();
a.BeginExecute(state =>
{
Console.WriteLine("finished");
((A)state.AsyncState).EndExecute(state);
}, a);
Console.ReadLine();
}
}
You don't need to do anything special, cause the caller should call you method async,
He define a new delegate pointing to you method, and use the .net to call your method asynchronously.
On BeginExecute you have to start the asynchronous operation (possibly start execute in a separate thread) and return as quick as possible. Execute has to call the AsyncCallback at the end of all operations so that who use the async operation gets aware and get the result. EndExecute has to stop a previously started async operation (possibly interrupting the thread launched by BeginExecute).
Without more details this is the best I can do.
If you want to run piece of code asynchronously, you should use BackgroundWorker. Unless of course, the code you are calling doesn't support asynchronous operation natively. Just like Read/Write methods or service calls.
If you want to notify, that the asynchronous operation has finished, use delegate or event callback.

Categories