.net - Why SynchronizationContext does not work properly? -
i have following code:
[testmethod] public void startworkinfirstthread() { if (synchronizationcontext.current == null) synchronizationcontext.setsynchronizationcontext( new synchronizationcontext()); var synccontext = synchronizationcontext.current; console.writeline("start work in first thread ({0})", thread.currentthread.managedthreadid); var action = ((action) dosomethinginsecondthread); action.begininvoke(callbackinsecondthread, synccontext); // continue own work } private static void dosomethinginsecondthread() { console.writeline("do in second thread ({0})", thread.currentthread.managedthreadid); } private void callbackinsecondthread(iasyncresult ar) { console.writeline("callback in second thread ({0})", thread.currentthread.managedthreadid); var synccontext = (synchronizationcontext) ar.asyncstate; synccontext.post(callbackinfirstthread, null); } private void callbackinfirstthread(object obj) { console.writeline("callback in first thread ({0})", thread.currentthread.managedthreadid); }
i expect last method executed in first thread, i.e. initial thread synchronizationcontext taken from, because call post()
method of context. i.e. this:
start work in first thread (28) in second thread (17) callback in second thread (17) callback in first thread (28)
isn't meaning of synchronizationcontext? have following output:
start work in first thread (28) in second thread (17) callback in second thread (17) callback in first thread (7)
what problem? go wrong synchronizationcontext or have misunderstanding?
update: call method unit test using resharper test runner.
see http://www.codeproject.com/kb/threads/synchronizationcontext.aspx
there answer need. must override synchronizationcontext
make handling operations.
read starting from:
notice dowork executed on thread 11, same thread run1. not of synchronizationcontext main thread. why? what's going on? well... part when realize nothing free in life. threads can't switch contexts between them, must have infrastructure built-in them in order so. ui thread, example, uses message pump, , within synchronizationcontext, leverages message pump sync ui thread.
Comments
Post a Comment