Created
October 6, 2017 16:26
-
-
Save EgorBo/d1942b662de1699ea0b9426289d4737f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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