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));
});
}
Related
So I'm working in Silverlight right now unfortunately for the first time. I'm decently familiar with callbacks, but I'm not entirely sure how to convert this method to be synchronous to perform logic on the order data.
I've been frequently told that making this synchronous was ill-advised, but my goal is to check if certain fields have been modified in the XAML UI and are different from what exists in the database. Then prompt for a reason for the change. If there is a better way to go about this, I'd love to know.
I'm in Silverlight 5 with .Net Framework 4.0 in VS 2013
Thank you! Here's the async order provider:
public void GetOrder(string ordNumber, Action<Func<OrderLoadResults>> callback)
{
String exStr = String.Format("{0}.{1}() --> received an empty value for",
this.GetType().Name,
MethodBase.GetCurrentMethod().Name);
if (ordNumber == null)
{
throw new ArgumentNullException("ordNumber", exStr);
}
if (callback == null)
{
throw new ArgumentNullException("callback", exStr);
}
IOrderServiceAsync channel = CreateChannel();
AsyncCallback asyncCallback = ar => GetOrderCallback(callback, ar);
channel.BeginGetOrderByOrdNumber(ordNumber, asyncCallback.ThreadSafe(), channel);
}
And here's what I'm doing with it:
public List<ATMModifiedFieldModel> CheckForATMModifiedFields()
{
if (!_order.Stops.Items.Any(x => x.ModelState == ModelState.Modified))
{
return null;
}
List<StopModel> oldStop = new List<StopModel>();
Provider.OrderProvider orderProvider = new Provider.OrderProvider();
//Looking to convert this method to sync to pull the order info out to compare against
//orderProvider.GetOrder(_order.Item.OrdHdrNumber.ToString(),getResult => OnGetOrderComplete(getResult));
List<ATMModifiedFieldModel> modifiedFields = new List<ATMModifiedFieldModel>();
foreach (StopModel stop in _order.Stops.Items)
{
if (stop.ModelState == ModelState.Modified)
{
foreach (string ATMFieldName in Enum.GetNames(typeof(ATMFields)))
{
string beforeValue = "before value"; //Should check the value in the database
string afterValue = stop.GetType().GetProperty(ATMFieldName).GetValue(stop, null).ToString();
if (beforeValue != afterValue)
{
modifiedFields.Add(new ATMModifiedFieldModel(ATMFieldName, beforeValue, afterValue, stop.StpNumber, "Stop"));
}
}
}
}
return modifiedFields;
}
I try to resolve the dreaded .WindowsPhone.exe!{<ID>}_Quiesce_Hang hang issue of my WinRT (Windows Phone 8.1) app.
At the moment I have the following handling of the Windows.UI.Xaml.Application.Suspending event:
private void App_Suspending(object iSender, SuspendingEventArgs iArgs)
{
SuspendingDeferral clsDeferral = null;
object objLock = new object();
try
{
clsDeferral = iArgs.SuspendingOperation.GetDeferral();
DateTimeOffset clsDeadline = iArgs.SuspendingOperation.Deadline;
//This task is to ensure that the clsDeferral.Complete()
//is called before the deadline.
System.Threading.Tasks.Task.Run(
async delegate
{
//Reducing the timeout by 1 second just in case.
TimeSpan clsTimeout = clsDeadline.Subtract(DateTime.UtcNow).Subtract(TimeSpan.FromSeconds(1));
if (clsTimeout.TotalMilliseconds > 100)
{
await System.Threading.Tasks.Task.Delay(clsTimeout);
}
DeferrerComplete(objLock, ref clsDeferral);
});
//Here I execute the suspending code i.e. I serializing the app
//state and save it in files. This may take more than clsTimeout
//on some devices.
...
//I do not call the Complete method here because the above
//suspending code is old-fashoin asynchronous i.e. not async but
//returns before the job is done.
//DeferrerComplete(objLock, ref clsDeferral);
}
catch
{
DeferrerComplete(objLock, ref clsDeferral);
}
}
private static void DeferrerComplete(object iLock, ref SuspendingDeferral ioDeferral)
{
lock (iLock)
{
if (ioDeferral != null)
{
try
{
ioDeferral.Complete();
}
catch
{
}
ioDeferral = null;
}
}
}
I have read the answer about the _Quiesce_Hang problem. I get the idea that it might be related to app storage activity. So my question is: what am I missing? Does my handling of the Suspending event look OK?
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.
I have a web reference which uses the Event-based Asynchronous Pattern. I am trying to convert this to use the Task based model so that I can use await/async. However I am having issues with this as it does not seem to do the call. I am using MonoTouch C# for this project.
Earlier I found this Stack overflow post which seemed to detail what I'm trying to do: How can I use async/await to call a webservice?
I managed to setup these methods and this is what my code looks like so far:
Authentication
var client = new AgentService();
GetUserDetailsCompletedEventArgs response = await client.GetUserDetailsAsyncTask(username, password);
if (response.Result != null)
// Do stuff
Agent Service Extensions
public static Task<GetUserDetailsCompletedEventArgs> GetUserDetailsAsyncTask(this AgentService client, string username, string password)
{
var source = new TaskCompletionSource<GetUserDetailsCompletedEventArgs>(null);
client.GetUserDetailsCompleted += (sender, e) => TransferCompletion(source, e, () => e);
client.GetUserDetailsAsync(username, password);
return source.Task;
}
private static void TransferCompletion(TaskCompletionSource<GetUserDetailsCompletedEventArgs> source, AsyncCompletedEventArgs e, Func<GetUserDetailsCompletedEventArgs> getResult)
{
if (e.UserState == source)
if (e.Cancelled)
source.TrySetCanceled();
else if (e.Error != null)
source.TrySetException(e.Error);
else
source.TrySetResult(getResult());
}
At the moment the GetUserDetailsAsyncTask method is called and the event handler is set but is never reached. After the await line is called the statement underneath it is never reached either and just skips to the end of the method. No error message is displayed and no exception is thrown. I'm not sure where I'm going wrong and I'd appreciate any guidance to help me solve this.
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.