SynchronizationContext.Current is null in Continuation on the main UI thread - c#

I've been trying to track down the following issue in a Winforms application:
The SynchronizationContext.Current is null in a task's continuation (i.e. .ContinueWith) which is run on the main thread (I expect the the current synchronization context to be System.Windows.Forms.WindowsFormsSynchronizationContext).
Here's the Winforms code demonstrating the issue:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TaskScheduler ts = TaskScheduler.FromCurrentSynchronizationContext(); // Get the UI task scheduler
// This line is required to see the issue (Removing this causes the problem to go away), since it changes the codeflow in
// \SymbolCache\src\source\.NET\4\DEVDIV_TFS\Dev10\Releases\RTMRel\ndp\clr\src\BCL\System\Threading\ExecutionContext.cs\1305376\ExecutionContext.cs
// at line 435
System.Diagnostics.Trace.CorrelationManager.StartLogicalOperation("LogicalOperation");
var task = Task.Factory.StartNew(() => { });
var cont = task.ContinueWith(MyContinueWith, CancellationToken.None, TaskContinuationOptions.None, ts);
System.Diagnostics.Trace.CorrelationManager.StopLogicalOperation();
}
void MyContinueWith(Task t)
{
if (SynchronizationContext.Current == null) // The current SynchronizationContext shouldn't be null here, but it is.
MessageBox.Show("SynchronizationContext.Current is null");
}
}
}
This is an issue for me since I attempt to use BackgroundWorker from the continuation, and the BackgroundWorker will use the current SynchronizationContext for its events RunWorkerCompleted and ProgressChanged. Since the current SynchronizationContext is null when I kick off the BackgroundWorker, the events don't run on the main ui thread as I intend.
My question:
Is this a bug in Microsoft's code, or have I made a mistake somewhere?
Additional info:
I'm using .Net 4.0 (I haven't yet tried this on .NET 4.5 RC)
I can reproduce this on both Debug/Release on any of x86/x64/Any CPU (on an x64 machine).
It reproduces consistently (I'd be interested if anyone can't reproduce it).
I have legacy code that uses the BackgroundWorker--so I can't easily change over to not using BackgroundWorker
I've confirmed that the code in MyContinueWith is running on the main ui thread.
I don't know precisely why the StartLogicalOperation call helps cause the issue, that's just what I narrowed it down to in my application.

The issue is fixed in .NET 4.5 RC (just tested it). So I assume it is a bug in .NET 4.0.
Also, I'm guessing that these posts are referencing the same issue:
How can SynchronizationContext.Current of the main thread become null in a Windows Forms application?
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/629d5524-c8db-466f-bc27-0ced11b441ba
That's unfortunate. Now I have to consider workarounds.
Edit:
From debugging into the .Net source, I have a little better understanding of when the issue would reproduce. Here's some relevant code from ExecutionContext.cs:
internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool ignoreSyncCtx)
{
// ... Some code excluded here ...
ExecutionContext ec = Thread.CurrentThread.GetExecutionContextNoCreate();
if ( (ec == null || ec.IsDefaultFTContext(ignoreSyncCtx)) &&
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) &&
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
executionContext.IsDefaultFTContext(ignoreSyncCtx))
{
callback(state);
}
else
{
if (executionContext == s_dummyDefaultEC)
executionContext = s_dummyDefaultEC.CreateCopy();
RunInternal(executionContext, callback, state);
}
}
The issue only reproduces when we get into the "else" clause which calls RunInternal. This is because the RunInternal ends up replacing the the ExecutionContext which has the effect of changing what the current SynchronizationContext:
// Get the current SynchronizationContext on the current thread
public static SynchronizationContext Current
{
get
{
SynchronizationContext context = null;
ExecutionContext ec = Thread.CurrentThread.GetExecutionContextNoCreate();
if (ec != null)
{
context = ec.SynchronizationContext;
}
// ... Some code excluded ...
return context;
}
}
So, for my specific case, it was because the line `executionContext.IsDefaultFTContext(ignoreSyncCtx)) returned false. Here's that code:
internal bool IsDefaultFTContext(bool ignoreSyncCtx)
{
#if FEATURE_CAS_POLICY
if (_hostExecutionContext != null)
return false;
#endif // FEATURE_CAS_POLICY
#if FEATURE_SYNCHRONIZATIONCONTEXT
if (!ignoreSyncCtx && _syncContext != null)
return false;
#endif // #if FEATURE_SYNCHRONIZATIONCONTEXT
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null && !_securityContext.IsDefaultFTSecurityContext())
return false;
#endif //#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_logicalCallContext != null && _logicalCallContext.HasInfo)
return false;
if (_illogicalCallContext != null && _illogicalCallContext.HasUserData)
return false;
return true;
}
For me, that was returning false due to _logicalCallContext.HasInfo was true. Here's that code:
public bool HasInfo
{
[System.Security.SecurityCritical] // auto-generated
get
{
bool fInfo = false;
// Set the flag to true if there is either remoting data, or
// security data or user data
if(
(m_RemotingData != null && m_RemotingData.HasInfo) ||
(m_SecurityData != null && m_SecurityData.HasInfo) ||
(m_HostContext != null) ||
HasUserData
)
{
fInfo = true;
}
return fInfo;
}
}
For me, this was returning true because HasUserData was true. Here's that code:
internal bool HasUserData
{
get { return ((m_Datastore != null) && (m_Datastore.Count > 0));}
}
For me, the m_DataStore would have items in it due to my call to Diagnostics.Trace.CorrelationManager.StartLogicalOperation("LogicalOperation");
In summary, it looks like there are several different ways you could get the bug to reproduce. Hopefully, this example will serve to help others in determining if they are running into this same bug or not.

Related

TaskScheduler.FromCurrentSynchronizationContext() throws an error on .Net 4 but not .Net4.5 [duplicate]

I've been trying to track down the following issue in a Winforms application:
The SynchronizationContext.Current is null in a task's continuation (i.e. .ContinueWith) which is run on the main thread (I expect the the current synchronization context to be System.Windows.Forms.WindowsFormsSynchronizationContext).
Here's the Winforms code demonstrating the issue:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TaskScheduler ts = TaskScheduler.FromCurrentSynchronizationContext(); // Get the UI task scheduler
// This line is required to see the issue (Removing this causes the problem to go away), since it changes the codeflow in
// \SymbolCache\src\source\.NET\4\DEVDIV_TFS\Dev10\Releases\RTMRel\ndp\clr\src\BCL\System\Threading\ExecutionContext.cs\1305376\ExecutionContext.cs
// at line 435
System.Diagnostics.Trace.CorrelationManager.StartLogicalOperation("LogicalOperation");
var task = Task.Factory.StartNew(() => { });
var cont = task.ContinueWith(MyContinueWith, CancellationToken.None, TaskContinuationOptions.None, ts);
System.Diagnostics.Trace.CorrelationManager.StopLogicalOperation();
}
void MyContinueWith(Task t)
{
if (SynchronizationContext.Current == null) // The current SynchronizationContext shouldn't be null here, but it is.
MessageBox.Show("SynchronizationContext.Current is null");
}
}
}
This is an issue for me since I attempt to use BackgroundWorker from the continuation, and the BackgroundWorker will use the current SynchronizationContext for its events RunWorkerCompleted and ProgressChanged. Since the current SynchronizationContext is null when I kick off the BackgroundWorker, the events don't run on the main ui thread as I intend.
My question:
Is this a bug in Microsoft's code, or have I made a mistake somewhere?
Additional info:
I'm using .Net 4.0 (I haven't yet tried this on .NET 4.5 RC)
I can reproduce this on both Debug/Release on any of x86/x64/Any CPU (on an x64 machine).
It reproduces consistently (I'd be interested if anyone can't reproduce it).
I have legacy code that uses the BackgroundWorker--so I can't easily change over to not using BackgroundWorker
I've confirmed that the code in MyContinueWith is running on the main ui thread.
I don't know precisely why the StartLogicalOperation call helps cause the issue, that's just what I narrowed it down to in my application.
The issue is fixed in .NET 4.5 RC (just tested it). So I assume it is a bug in .NET 4.0.
Also, I'm guessing that these posts are referencing the same issue:
How can SynchronizationContext.Current of the main thread become null in a Windows Forms application?
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/629d5524-c8db-466f-bc27-0ced11b441ba
That's unfortunate. Now I have to consider workarounds.
Edit:
From debugging into the .Net source, I have a little better understanding of when the issue would reproduce. Here's some relevant code from ExecutionContext.cs:
internal static void Run(ExecutionContext executionContext, ContextCallback callback, Object state, bool ignoreSyncCtx)
{
// ... Some code excluded here ...
ExecutionContext ec = Thread.CurrentThread.GetExecutionContextNoCreate();
if ( (ec == null || ec.IsDefaultFTContext(ignoreSyncCtx)) &&
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
SecurityContext.CurrentlyInDefaultFTSecurityContext(ec) &&
#endif // #if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
executionContext.IsDefaultFTContext(ignoreSyncCtx))
{
callback(state);
}
else
{
if (executionContext == s_dummyDefaultEC)
executionContext = s_dummyDefaultEC.CreateCopy();
RunInternal(executionContext, callback, state);
}
}
The issue only reproduces when we get into the "else" clause which calls RunInternal. This is because the RunInternal ends up replacing the the ExecutionContext which has the effect of changing what the current SynchronizationContext:
// Get the current SynchronizationContext on the current thread
public static SynchronizationContext Current
{
get
{
SynchronizationContext context = null;
ExecutionContext ec = Thread.CurrentThread.GetExecutionContextNoCreate();
if (ec != null)
{
context = ec.SynchronizationContext;
}
// ... Some code excluded ...
return context;
}
}
So, for my specific case, it was because the line `executionContext.IsDefaultFTContext(ignoreSyncCtx)) returned false. Here's that code:
internal bool IsDefaultFTContext(bool ignoreSyncCtx)
{
#if FEATURE_CAS_POLICY
if (_hostExecutionContext != null)
return false;
#endif // FEATURE_CAS_POLICY
#if FEATURE_SYNCHRONIZATIONCONTEXT
if (!ignoreSyncCtx && _syncContext != null)
return false;
#endif // #if FEATURE_SYNCHRONIZATIONCONTEXT
#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_securityContext != null && !_securityContext.IsDefaultFTSecurityContext())
return false;
#endif //#if FEATURE_IMPERSONATION || FEATURE_COMPRESSEDSTACK
if (_logicalCallContext != null && _logicalCallContext.HasInfo)
return false;
if (_illogicalCallContext != null && _illogicalCallContext.HasUserData)
return false;
return true;
}
For me, that was returning false due to _logicalCallContext.HasInfo was true. Here's that code:
public bool HasInfo
{
[System.Security.SecurityCritical] // auto-generated
get
{
bool fInfo = false;
// Set the flag to true if there is either remoting data, or
// security data or user data
if(
(m_RemotingData != null && m_RemotingData.HasInfo) ||
(m_SecurityData != null && m_SecurityData.HasInfo) ||
(m_HostContext != null) ||
HasUserData
)
{
fInfo = true;
}
return fInfo;
}
}
For me, this was returning true because HasUserData was true. Here's that code:
internal bool HasUserData
{
get { return ((m_Datastore != null) && (m_Datastore.Count > 0));}
}
For me, the m_DataStore would have items in it due to my call to Diagnostics.Trace.CorrelationManager.StartLogicalOperation("LogicalOperation");
In summary, it looks like there are several different ways you could get the bug to reproduce. Hopefully, this example will serve to help others in determining if they are running into this same bug or not.

Releasing a Mutex

I have a web application that needs to utilise an application cache to store data (due to the high overhead of obtaining that data ona request by request basis). See previous post at https://stackoverflow.com/a/16961962/236860
This approach seems to work well, but I am seeing the following occasional errors in the web site's error:
System.ApplicationException: Object synchronization method was called from an
unsynchronized block of code.
at System.Threading.Mutex.ReleaseMutex()
at InboxInsight.Web.Web_Controls.Twitter.TwitterFeed.GetTwitterData(HttpContext context)
at InboxInsight.Web.Web_Controls.Twitter.TwitterFeed.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
For reference, here is the code block:
public string GetData(HttpContext context)
{
var cache = context.Cache;
Mutex mutex = null;
string data = (string)cache[CacheKey];
// Start check to see if available on cache
if (data == null)
{
try
{
// Lock base on resource key
// (note that not all chars are valid for name)
mutex = new Mutex(true, CacheKey);
// Wait until it is safe to enter (someone else might already be
// doing this), but also add 30 seconds max.
mutex.WaitOne(30000);
// Now let's see if some one else has added it...
data = (string)cache[CacheKey];
// They did, so send it...
if (data != null)
{
return data;
}
// Still not there, so now is the time to look for it!
data = GetSlowFeed(context);
cache.Remove(CacheKey);
cache.Add(CacheKey, data, null, GetExpiryDate(),
TimeSpan.Zero, CacheItemPriority.Normal, null);
}
finally
{
// Release the Mutex.
if (mutex != null)
{
mutex.ReleaseMutex();
}
}
}
return data;
}
From what I have researched, it suggests this problem is caused by a process thread trying to release a Mutex that it didn't create, but I don't understand how this could happen.
Can anyone suggest how I can re-structure the code to avoid this problem?
You are not handling the case whereby the mutex.WaitOne returns false ie times out. If WaitOne returns false you don't own the mutex therefore you don't need to release it.
bool iOwnTheMutex;
try {
// set up mutex here...
iOwnTheMutex = mutex.WaitOne(2000);
if (iOwnTheMutex) {
// do what you need to do
}
}
finally {
if (mutex != null && iOwnTheMutex) {
mutex.ReleaseMutex();
}
}

Checking internet connectivity in Windows8 via C# fails

I'm trying to test the Internet connection in Windows8 from my C# application. I have a variable of type Boolean that returns me the connection status. When the boolean is true: do nothing. When the boolean becomes false, load my "NetworkDisconection" page. However, when I debug this line:
if (this.Frame != null)
I get an exception:
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
Yeah, this method is on a different thread. How can I resolve this?
private bool bConection;
public HUB()
{
this.InitializeComponent();
bConection = NetworkInformation.GetInternetConnectionProfile()!= null;
NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
}
void NetworkInformation_NetworkStatusChanged(object sender)
{
if (NetworkInformation.GetInternetConnectionProfile() == null)
{
if (bConection == false)
{
bConection = true;
}
}
else
{
if (bConection == true)
{
bConection = false;
if (this.Frame != null)
{
Frame.Navigate(typeof(NetworkDisconection));
}
}
}
}
Use the following code and it should fix your problem...
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
if (this.Frame != null)
{
Frame.Navigate(typeof(NetworkDisconection));
}
});
You should be able to acquire the Dispatcher directly since it looks like your code is in the code-behind of a XAML page (reference to this.Frame).
Tons of good info can be found in the C# Win8 Dev Forums. Search for Dispatcher and you will find several discussions on it. As always, check out GenApp for other great resources.
The NetworkInformation.NetworkStatusChanged event is raised on a non-UI thread. Similar to WinForms and WPF, you are still limited to accessing controls on the UI thread.
To get around this aspect, you'll have to invoke the UI thread similar to how you would on WinForms or WPF using this.Invoke/this.Dispatcher.Invoke.
At first you may try to use Window.Current.Dispatcher.RunAsync() but you will notice that Window.Current is always null here.
Instead, you should use CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync() in the Windows.ApplicationModel.Core namespace. Yeah, that's quite a mouthful for sure so I recommend this helper method in App.cs.
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
public static IAsyncAction ExecuteOnUIThread(DispatchedHandler action)
{
var priority = CoreDispatcherPriority.High;
var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
return dispatcher.RunAsync(priority, action);
}
I would also recommend this helper method too:
public static bool CheckInternetAccess()
{
var profile = NetworkInformation.GetInternetConnectionProfile();
if (profile == null) return false;
var connectivityLevel = profile.GetNetworkConnectivityLevel();
return connectivityLevel.HasFlag(NetworkConnectivityLevel.InternetAccess);
}
And finally:
async void NetworkInformation_NetworkStatusChanged(object sender)
{
var isConnected = CheckInternetAccess();
await ExecuteOnUIThread(() =>
{
if (!isConnected && this.Frame != null)
this.Frame.Navigate(typeof(ConnectionLostPage));
});
}

How to make Code Contracts believe that variable is not null?

I have some factory method
public T Create<T> () where T : class
{
Contract.Ensures(Contract.Result<T>() != null);
T result = this.unityContainer.Resolve<T>();
return result;
}
The I try to build the project i get the warning:
CodeContracts: ensures unproven: Contract.Result() != null
I understand that IUnityContainer interface does not have any contracts so Code Contracts think that varible may be null and there is no way to prove that Create() will return not null result.
How in this case I can make Code Contracts belive that result variable is not null?
I first tried to call Contract.Assert
public T Create<T> () where T : class
{
Contract.Ensures(Contract.Result<T>() != null);
T result = this.unityContainer.Resolve<T>();
Contract.Assert(result != null);
return result;
}
But it takes me another warning:
CodeContracts: assert unproven
I tried make check for null and this makes all warnings gone:
public T Create<T> () where T : class
{
Contract.Ensures(Contract.Result<T>() != null);
T result = this.unityContainer.Resolve<T>();
if (result == null)
{
throw new InvalidOperationException();
}
return result;
}
But i'm not sure this is good solution to throw exception manually. May be there is some way to solve problem using Code Contracts only?
Thank you.
I think you want Contract.Assume:
Contract.Assume(result != null);
From the docs:
Instructs code analysis tools to assume that the specified condition is true, even if it cannot be statically proven to always be true.
This will still validate the result at execution time if you have the rewriter appropriately configured.
Like if((result ?? 0) == 0){}
To make this more clear (readable) you can define an extension method.
Edit
#allentracks answer is more precise for your question

How can this error be possible in this code - error : Object reference not set to an instance of an object

This is how i call that error given function
var CrawlPage = Task.Factory.StartNew(() =>
{
return crawlPage(srNewCrawledUrl);
});
var GetLinks = CrawlPage.ContinueWith(resultTask =>
{
if (CrawlPage.Result == null)
{
return null;
}
else
{
return ReturnLinks(CrawlPage.Result, srNewCrawledUrl, srNewCrawledPageId);
}
});
This is the error i really don't understand how is that possible. I am using local assigned variables so variables should be thread safe for all threads. Am i incorrect ?
this is the error image :
you better validate InnerHtml is null or not before calling
var GetLinks = CrawlPage.ContinueWith(resultTask =>
{
if (CrawlPage.Result == null || CrawlPage.Result.DocumentNode == null || CrawlPage.Result.DocumentNode.InnerHtml == null)
{
return null;
}
else
{
return ReturnLinks(CrawlPage.Result, srNewCrawledUrl, srNewCrawledPageId);
}
});
Or check this on ReturnLinks method
I am using local assigned variables so variables should be thread safe for all threads. Am i incorrect ?
The fact that you are making a reference local does not mean that the object this reference points to suddenly becomes local. Other thread (not shown in your question?) might still be mutating the HtmlDocument object at just the wrong moment (between hdDoc.DocumentNode != null and hdDoc.DocumentNode.InnerHtml != null).

Categories