Skip to content

Instantly share code, notes, and snippets.

@EgorBo
Created October 6, 2017 16:26
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 EgorBo/d1942b662de1699ea0b9426289d4737f to your computer and use it in GitHub Desktop.
Save EgorBo/d1942b662de1699ea0b9426289d4737f to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
namespace ConsoleApplication
{
internal class Program
{
const int UnexpectedTimeoutMilliseconds = 30 * 1000;
public static void Main(string[] args)
{
var asyncLocal = new AsyncLocal<int>();
asyncLocal.Value = 1;
var obj = new object();
var registerWaitEvent = new AutoResetEvent(false);
var threadDone = new AutoResetEvent(false);
RegisteredWaitHandle registeredWaitHandle = null;
Exception backgroundEx = null;
int backgroundAsyncLocalValue = 0;
Action<bool, Action> commonBackgroundTest =
(isRegisteredWaitCallback, test) =>
{
try
{
if (isRegisteredWaitCallback)
{
RegisteredWaitHandle toUnregister = registeredWaitHandle;
registeredWaitHandle = null;
toUnregister.Unregister(threadDone);
}
test();
backgroundAsyncLocalValue = asyncLocal.Value;
}
catch (Exception ex)
{
backgroundEx = ex;
}
finally
{
if (!isRegisteredWaitCallback)
{
threadDone.Set();
}
}
};
Action<bool> waitForBackgroundWork =
isWaitForRegisteredWaitCallback =>
{
if (isWaitForRegisteredWaitCallback)
{
registerWaitEvent.Set();
}
threadDone.WaitOne(30 * 1000);
};
ThreadPool.QueueUserWorkItem(state => commonBackgroundTest(false, () =>{}), obj);
waitForBackgroundWork(false);
ThreadPool.UnsafeQueueUserWorkItem(state => commonBackgroundTest(false, () =>{}), obj);
waitForBackgroundWork(false);
registeredWaitHandle =
ThreadPool.RegisterWaitForSingleObject(registerWaitEvent,
(state, timedOut) => commonBackgroundTest(true, () => {}),
obj, UnexpectedTimeoutMilliseconds, false);
waitForBackgroundWork(true);
registeredWaitHandle =
ThreadPool.UnsafeRegisterWaitForSingleObject(registerWaitEvent,
(state, timedOut) => commonBackgroundTest(true, () => {}),
obj, UnexpectedTimeoutMilliseconds, false);
waitForBackgroundWork(true);
Console.WriteLine("Should be 0: " + backgroundAsyncLocalValue);
//.NET: 1
//Mono: 0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment