Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mayerwin
Forked from svick/Program.cs
Created September 3, 2012 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayerwin/3610738 to your computer and use it in GitHub Desktop.
Save mayerwin/3610738 to your computer and use it in GitHub Desktop.
SO Task inlining
Sometimes:
2012-09-03 16:44:48.8846|INFO|CR.UnitTests.Behaviors.Test1::[9] Entering Test, stop = False.
2012-09-03 16:44:48.8846|INFO|CR.UnitTests.Behaviors.Test1::[9] Entering Test, stop = True.
2012-09-03 16:44:48.8846|INFO|CR.UnitTests.Behaviors.Test1::[9] Exiting Test by stopping.
2012-09-03 16:44:48.8846|INFO|CR.UnitTests.Behaviors.Test1::[9] Exiting Test normally.
2012-09-03 16:44:48.8846|INFO|CR.UnitTests.Behaviors.Test2::[10] Entering Test, stop = False.
2012-09-03 16:44:48.8846|INFO|CR.UnitTests.Behaviors.Test2::[10] Entering Test, stop = True.
2012-09-03 16:44:48.8846|INFO|CR.UnitTests.Behaviors.Test2::[10] Exiting Test by stopping.
2012-09-03 16:44:48.9166|INFO|CR.UnitTests.Behaviors.Test2::[10] Exiting Test normally.
Sometimes, it deadlocks on Test2.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1 {
class Program {
static void Main() {
Task.Factory.StartNew(() => {
Task.Factory.StartNew(() => Test1()).Wait();
Task.Factory.StartNew(() => Test2()).Wait(); //Sometimes works, sometimes deadlocks.
});
}
static object TestLock = new object();
public static void Test1(bool stop = false) {
Console.WriteLine("[{0}] Entering Test, stop = {1}.", Thread.CurrentThread.ManagedThreadId, stop);
Task t;
lock (TestLock) {
if (stop) {
Console.WriteLine("[{0}] Exiting Test by stopping.", Thread.CurrentThread.ManagedThreadId);
return;
}
t = Task.Factory.StartNew(() => { Test1(stop: true); });
}
t.Wait();
Console.WriteLine("[{0}] Exiting Test normally.", Thread.CurrentThread.ManagedThreadId);
}
public static void Test2(bool stop = false) {
Console.WriteLine("[{0}] Entering Test, stop = {1}.", Thread.CurrentThread.ManagedThreadId, stop);
Task t;
lock (TestLock) {
if (stop) {
Console.WriteLine("[{0}] Exiting Test by stopping.", Thread.CurrentThread.ManagedThreadId);
return;
}
t = Task.Factory.StartNew(() => { Test2(stop: true); });
}
t.Wait();
Console.WriteLine("[{0}] Exiting Test normally.", Thread.CurrentThread.ManagedThreadId);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment