C# backgroundWorker wait ReportProgress - c#

Is there any way to "wait" for the ReportProgress method to end?
I'm updating a list on the ReportProgress method that after i'm calling to the method i'm using that list, which is wrong unless the ReportProgress has finished.
#region addNodesToUi
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ));
nodes = new List<NodeViewModel>();
try
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ));
Debug.WriteLine("Success creating new nodeViewModel");
}
catch (Exception ex)
{
logger.addMessage("Error in creating new nodeViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in creating new nodeViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
}
int width = 0;
int height = 0;
int i = 0;
ObservableCollection<Common.Model.System> allSystems = new ObservableCollection<Common.Model.System>();
lock (mainNetLocker)
{
allSystems = MainNet.Systems;
}
foreach (var system in allSystems.ToList())
{
Debug.WriteLine("inside Foreach in system: " + system.Name + " interface " + system.Interfaces.Count + " structs " + system.Structs.Count);
if (nodes == null)
Debug.WriteLine("FUUUCCKKKK!");
try
{
Debug.WriteLine("Before add node");
try
{
Debug.WriteLine("trying to add: " + system.Name + " " + system.InputNum + " " + system.OutputNum + " " + system.Interfaces.Count + " " + system.Enums.Count + " " + system.Structs.Count);
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => nodes.Add(CreateNode(system.Name, new Point(width, height), false, system.InputNum, system.OutputNum, system.Interfaces, system.Enums, system.Structs, update))));
nodes.Add(CreateNode(system.Name, new Point(width, height), false, system.InputNum, system.OutputNum, system.Interfaces, system.Enums, system.Structs, update));
//bw.ReportProgress(i++, tempn
}
catch (Exception ex)
{
logger.addMessage("Error adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Debug.WriteLine("Success adding new node to list");
}
catch (Exception ex)
{
logger.addMessage("Error in adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
}
width += 150;
if (width >= 700)
{
width = 0;
height += 100;
}
}
if (MainWindow.IsFlow)
{
Object[] getInterfacesWithGuidToFlowParam = new Object[1];
getInterfacesWithGuidToFlowParam[0] = MainWindow.GuidToFlow;
try
{
interfacesForFlow = (List<String>)getInterfacesWithGuidToFlow.Invoke(sqlDB, getInterfacesWithGuidToFlowParam);
Debug.WriteLine("Success getInterfacesWithGuidToFlow " + interfacesForFlow.Count);
}
catch (Exception ex)
{
logger.addMessage("Error in getInterfacesWithGuidToFlow : " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getInterfacesWithGuidToFlow : " + ex.Message + " Inner: " + ex.InnerException.Message);
}
}
foreach (var system in allSystems.ToList())
{
if (system.OutputNum > 0) //this system has an output connector
{
//int i = 0;
foreach (var outId in system.Outputs) //loop throw all systems ids that current system is connected to
{
Debug.WriteLine("out id = " + outId);
ConnectionViewModel connection = null;
try
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection = new ConnectionViewModel()));
connection = new ConnectionViewModel();
Debug.Write("Success creating new ConnectionViewModel");
}
catch (Exception ex)
{
logger.addMessage("Error in creating new ConnectionViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in creating new ConnectionViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Object[] getSystemNameParams = new Object[1];
getSystemNameParams[0] = outId;
string destSystemName = "";
try
{
destSystemName = (String)getSystemName.Invoke(sqlDB, getSystemNameParams);
}
catch (Exception ex)
{
logger.addMessage("Error in getSystemName: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSystemName: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
NodeViewModel sourceItem = null;
NodeViewModel destItem = null;
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => sourceItem = nodes.Find(x => x.Name == system.Name)));
lock (networkLocker)
{
sourceItem = nodes.Find(x => x.Name == system.Name);
}
//int sourceId = nodes.FindIndex(sourceItem);
Debug.Write("Success creating new sourceItem");
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => destItem = nodes.Find(x => x.Name == destSystemName)));
lock (networkLocker)
{
destItem = nodes.Find(x => x.Name == destSystemName);
}
Debug.Write("Success creating new destItem");
try
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => destItem.InputSystems.Add(sourceItem.Name)));
destItem.InputSystems.Add(sourceItem.Name);
}
catch (Exception ex)
{
logger.addMessage("Error adding input system: " + ex.Message);
Debug.Write("Error adding input system: " + ex.Message);
}
try
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => sourceItem.OutputSystems.Add(destItem.Name)));
sourceItem.OutputSystems.Add(destItem.Name);
}
catch (Exception ex)
{
logger.addMessage("Error adding OutputSystems: " + ex.Message);
Debug.Write("Error adding OutputSystems: " + ex.Message);
}
Debug.Write("Success bah");
//int destId = nodes.FindIndex(destItem);
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.SourceConnector = sourceItem.OutputConnectors[i++]));
connection.SourceConnector = sourceItem.OutputConnectors[i++];
Debug.Write("Success bah");
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.DestConnector = destItem.InputConnectors[destItem.InputConnectors.Count - 1]));
connection.DestConnector = destItem.InputConnectors[destItem.InputConnectors.Count - 1];
Debug.Write("Success bah");
// Add the connection to the view-model.
//
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.Type = ConnectionViewModel.ConnectorType.REGULAR));
connection.Type = ConnectionViewModel.ConnectorType.REGULAR;
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => this.Network.Connections.Add(connection)));
//Debug.Write("Success bah");
if (MainWindow.IsFlow)
{
Debug.WriteLine("inside IsFlow!");
foreach (var #interface in interfacesForFlow)
{
String[] systems = #interface.Split('_');
Debug.WriteLine("Flow from: " + systems[0] + " To " + systems[1]);
if (systems[0].Equals(sourceItem.Name) && systems[1].Equals(destItem.Name))
connection.Type = ConnectionViewModel.ConnectorType.FLOW;
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.Type = ConnectionViewModel.ConnectorType.FLOW));
}
}
lock (networkLocker)
{
bw.ReportProgress(2, connection);
}
}
}
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ww.Close()));
//bw2.ReportProgress(100);
}
#endregio
Well i couldn't upload the whole method, this is the part that addes the nodes to thee UI, the Updated from Database can be seen here: Look at the edit below

If you want to serialize access to your ReportProgress method AND the worker method cannot be changed, you can change ReportProgress to this...
private readonly Semaphore _throttle = new Semaphore(1,1);
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
_throttle.WaitOne();
if (e.ProgressPercentage == 1) //update nodes
{
this.Network.Nodes.Add((NodeViewModel)e.UserState);
}
else if (e.ProgressPercentage == 2) //update connections
{
this.Network.Connections.Add((ConnectionViewModel)e.UserState);
}
else if (e.ProgressPercentage == 3)
{
this.Network.Connections.Clear();
this.Network.Nodes.Clear();
}
else if (e.ProgressPercentage == 4)
{
MainNet.Systems.Add((Common.Model.System)e.UserState);
}
}
finally
{
_throttle.Release();
}
}
This approach adds a throttle to the callback that will force callers to wait until the ReportProgress has finished. Only one caller can enter the body of the method at a time which is what you want to achieve. The drawback is that the queue will block the UI, but that outcome is IMPLICIT in your question anyway.
The Semaphore docs are here

Related

How can you prevent UI in C# WPF from hanging?

I have a C# script that connects to remote server and display all members of a local group. The script is running but it hangs upon searching/connecting to the server.
I have the following required fields in the WPF:
ServerList (combobox)
UserAccess (textbox multiline)
DataGridResult (DataGrid for output)
Here's my async/await script, but still hangs:
private async void ButtonRun_Click(object sender, EventArgs e)
{
if (UserAccess.SelectedItem == null)
{
MessageBox.Show("What Access are we going to display?");
return;
}
string[] separate = new string[] { "\r\n" };
string[] strServers = ServerList.Text.Split(separate, StringSplitOptions.RemoveEmptyEntries);
if (strServers == null || ServerList.Text == "")
{
MessageBox.Show("There are no Servers Defined!");
return;
}
int strServersCount = ServerList.LineCount;
DataTable temptable = new DataTable();
temptable.Columns.Add("Server");
temptable.Columns.Add("Comments");
ButtonRun.IsEnabled = false;
await Task.Run(() =>
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
for (var i = 0; i <= strServersCount - 1; i++)
{
try
{
DirectoryEntry directoryServers = new DirectoryEntry("WinNT://" + strServers[i] + ",computer");
DirectoryEntry directoryGroup = directoryServers.Children.Find(UserAccess.Text + ",group");
object members = directoryGroup.Invoke("members", null);
foreach (object GroupMember in (IEnumerable)members)
{
DirectoryEntry directoryMember = new DirectoryEntry(GroupMember);
Console.WriteLine(directoryMember.Name + " | " + directoryMember.Path);
temptable.Rows.Add(strServers[i], directoryMember.Name + " | " + directoryMember.Path);
}
}
catch (Exception ex)
{
temptable.Rows.Add(strServers[i], "Error: " + ex.InnerException + " | " + ex.Message);
}
DataGridResult.ItemsSource = temptable.DefaultView;
ButtonRun.IsEnabled = true;
}
}));
});
}
An attempt to fix this, untested:
string userAccessText = UserAccess.Text;
await Task.Run(() =>
{
//this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
// {
for (var i = 0; i <= strServersCount - 1; i++)
{
try
{
DirectoryEntry directoryServers = new DirectoryEntry("WinNT://" + strServers[i] + ",computer");
DirectoryEntry directoryGroup = directoryServers.Children.Find(userAccessText + ",group");
object members = directoryGroup.Invoke("members", null);
foreach (object GroupMember in (IEnumerable)members)
{
DirectoryEntry directoryMember = new DirectoryEntry(GroupMember);
Console.WriteLine(directoryMember.Name + " | " + directoryMember.Path);
temptable.Rows.Add(strServers[i], directoryMember.Name + " | " + directoryMember.Path);
}
}
catch (Exception ex)
{
temptable.Rows.Add(strServers[i], "Error: " + ex.InnerException + " | " + ex.Message);
}
// DataGridResult.ItemsSource = temptable.DefaultView;
// ButtonRun.IsEnabled = true;
}
// })); // End of Invoke
});
DataGridResult.ItemsSource = temptable.DefaultView;
ButtonRun.IsEnabled = true;
The basic idea is to put all the non-GUI stuff inside the Task, and then consume the data in the async OnClick method after awaiting that Task.

Error log inside thread not working sometime

I am calling following method inside thread. inside method i have written logs which writes some variable values in notepad file.
Problem : Sometime last log of method do not log anything. ie last line not exucuting sometime. i am not able to understand problem. please guide me if there are issue somewhere.
This is web application hosted in iis server.
Function :
public bool ResetEmployeeAssignedCoursesByRole()
{
bool bReturn = false;
DbTransactionHelper dbTransactionHelper = new DbTransactionHelper();
dbTransactionHelper.BeginTransaction();
try
{
// this line execuete fine
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Started " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
StringBuilder sbQueryEmployeeCourse = new StringBuilder();
sbQueryEmployeeCourse.Append(" set #roleID = " + roleID + "; ");
sbQueryEmployeeCourse.Append(" set #courseID = " + courseID + "; ");
sbQueryEmployeeCourse.Append(" set #inActiveReason = " + inActiveReason + "; ");
sbQueryEmployeeCourse.Append(" set #lastRecordUpdateSource = " + lastRecordUpdateSource + "; ");
sbQueryEmployeeCourse.Append(" call sp_Reset_EmpAssignedCoursesByRole (#roleID, #courseID, #inActiveReason, #lastRecordUpdateSource); ");
DataTable dtEmployeeCourse = dbTransactionHelper.GetDataTable(BusinessUtility.GetString(sbQueryEmployeeCourse), CommandType.Text, null
);
dbTransactionHelper.CommitTransaction();
bReturn = true;
// this line not execuete sometime.
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
}
catch (Exception ex)
{
ErrorLog.createRoleLog("Add Role ID " + BusinessUtility.GetString(roleID));
dbTransactionHelper.RollBackTransaction();
ErrorLog.createRoleLog("Add Course ID " + BusinessUtility.GetString(courseID));
ErrorLog.createRoleLog(ex.ToString());
}
return bReturn;
}
Calls method like below :
Thread t = new Thread(ResetEmployeeAssignedCoursesByRole);
t.Start();
FUNCTION createRoleLog :
public static void createRoleLog(string errorMessage, int empHdrID = 0)
{
try
{
//string path = BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogsDiractory")) + "Log" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
string path = BusinessUtility.GetString(ErrorLog.ErrorLogPath) + "RoleLog" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
if (BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogError")).ToString().ToUpper() == "TRUE")
{
if (!File.Exists(path))
{
StreamWriter sw = File.CreateText(path);
sw.Close();
}
//using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))
//{
// sw.WriteLine("-------- " + DateTime.Now + " --------");
// sw.WriteLine(errorMessage);
// sw.WriteLine("------------------------");
// sw.Close();
//}
if (!IsFileLocked(new FileInfo(path)))
{
using (FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (System.IO.StreamWriter sw = new StreamWriter(stream))
{
if (empHdrID != 0)
{
sw.WriteLine("-------- [empHdrID: " + empHdrID + "] " + DateTime.Now + " --------");
}
else
{
sw.WriteLine("-------- " + DateTime.Now + " --------");
}
sw.WriteLine(errorMessage);
sw.WriteLine("------------------------");
sw.Close();
}
}
}
else
{
}
}
}
catch (Exception ex)
{
//throw ex;
}
}
Last line of function which not execution sometime is :
** this line not execuete sometime.**
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);

Failed to marshal the objective-c object

I am having a tough time with the following error:
Failed to marshal the Objective-C object 0x17109780 (type:
SMBSC_iOS_EddystoneManagerDelegate). Could not find an existing
managed instance for this object, nor was it possible to create a new
managed instance (because the type
'SMBSC.iOS.EddystoneManagerDelegate' does not have a constructor that
takes one IntPtr argument).
I have added the constructor it is looking for, but the application still crashes with this error.
I am working with the Kontakt Xamarin component.
I am creating a new scan with the following line:
manager = new KTKEddystoneManager(new EddystoneManagerDelegate() { ScanID = ID });
Here is the delegate that is causing the error:
public class EddystoneManagerDelegate : KTKEddystoneManagerDelegate
{
public static int closestRssi { get; set; }
public static string closestInstance { get; set; }
public int ScanID { get; set; }
public EddystoneManagerDelegate()
{
}
public EddystoneManagerDelegate(IntPtr handle) : base(handle)
{
}
public override void DidFailToStartDiscovery(KTKEddystoneManager manager, NSError error)
{
Console.WriteLine("Eddystone discovery failed with error: " + error.Description);
}
public override void DidUpdateEddystone(KTKEddystoneManager manager, KTKEddystone eddystone, KTKEddystoneFrameType frameType)
{
string bkpnt = "";
}
public override void DidDiscoverEddystones(KTKEddystoneManager manager, NSSet<KTKEddystone> eddystones, KTKEddystoneRegion region)
{
try
{
Console.WriteLine("");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
int i = 0;
foreach (SavedPoint p in App.discoveredBeaconList)
{
i += 1;
Console.WriteLine("Existing Beacon List: " + p.BeaconInstanceID + " - " + p.BeaconTruckDesc + " - " + p.RSSI);
}
if (App.closestBeaconForTracking != null)
{
Console.WriteLine("Selected Beacon Before Logic: " + App.closestBeaconForTracking.instanceID + " RSSI: " + App.closestBeaconForTracking.RSSI);
}
else
{
Console.WriteLine("Selected Beacon Before Logic: no beacon selected");
}
App.singleOutputValue = "";
Console.WriteLine("Discovered " + eddystones.Count + " eddystones");
App.beaconTimer = DateTime.Now;
App.trackingBeaconTimer = DateTime.Now;
MessagingCenter.Send<App>(App.instance, "Output");
if (eddystones.Count == 1)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("First Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " First Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 2)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Second Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Second Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 3)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Third Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Third Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
else if (eddystones.Count == 4)
{
TimeSpan span = DateTime.Now - EddystoneiOS.StartTime;
Console.WriteLine("Fourth Stone found in " + span.TotalSeconds + " seconds");
App.outputValue += " Fourth Stone found in " + span.TotalSeconds + " seconds; " + ScanID + "; " + DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine;
MessagingCenter.Send<App>(App.instance, "Output");
}
App.closestBeaconForTracking = null;
foreach (var stone in eddystones)
{
KTKEddystone eddystone = (KTKEddystone)stone;
Console.WriteLine(eddystone.RSSI + ", " + eddystone.EddystoneUID.InstanceID);
App.outputValue += " " + eddystone.RSSI + ", " + ScanID + "; " + eddystone.EddystoneUID.InstanceID + Environment.NewLine;
App.instanceID = eddystone.EddystoneUID.InstanceID;
App.NameSpaceID = eddystone.EddystoneUID.NamespaceID;
App.rssi = eddystone.RSSI.Int32Value;
App.BeaconCount = (int)eddystones.Count;
App.lastBeaconTime = DateTime.Now.ToString();
if (App.isViewingBeacons)
{
MessagingCenter.Send<App>(App.instance, "StoneForBeaconList");
}
MapApp.Beacon beacon = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
if (beacon != null)
{
beacon.RSSI = eddystone.RSSI.Int32Value;
SavedPoint point = new SavedPoint() { BeaconID = beacon.BeaconID, BeaconInstanceID = beacon.instanceID, BeaconName = beacon.Name, BeaconNameSpaceID = beacon.namespaceID, RSSI = beacon.RSSI, BeaconTruckDesc = beacon.truckDesc };
point.LastSeenTime = DateTime.Now;
if (App.discoveredBeaconList == null)
{
App.discoveredBeaconList = new List<SavedPoint>();
}
if (!App.discoveredBeaconList.Exists(x => x.BeaconInstanceID == point.BeaconInstanceID) && beacon.RSSI != 0)
{
App.discoveredBeaconList.Add(point);
}
else
{
foreach (SavedPoint p in App.discoveredBeaconList)
{
if (p.BeaconInstanceID == point.BeaconInstanceID && beacon.RSSI != 0)
{
p.LastSeenTime = DateTime.Now;
p.RSSI = point.RSSI;
}
}
}
}
if (eddystone.RSSI.Int32Value != 0)
{
if (string.IsNullOrWhiteSpace(App.closestBeaconOutput))
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
if (closestInstance == eddystone.EddystoneUID.InstanceID)
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
if ((int)eddystone.RSSI > closestRssi)
{
App.closestBeaconOutput = eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI;
closestRssi = (int)eddystone.RSSI;
closestInstance = (string)eddystone.EddystoneUID.InstanceID;
MessagingCenter.Send<App>(App.instance, "topOutput");
}
//if(App.closestBeaconForTracking == null)
//{
// App.closestBeaconForTracking = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
// if(App.closestBeaconForTracking != null)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
//}
//if (App.closestBeaconForTracking != null)
//{
// if (App.closestBeaconForTracking.instanceID.ToLower() == eddystone.EddystoneUID.InstanceID && App.closestBeaconForTracking.namespaceID.ToLower() == eddystone.EddystoneUID.NamespaceID)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
// if (eddystone.RSSI.Int32Value > App.closestBeaconForTracking.RSSI)
// {
// App.closestBeaconForTracking = App.Database.GetBeaconByID(eddystone.EddystoneUID.InstanceID.ToLower(), eddystone.EddystoneUID.NamespaceID.ToUpper());
// if (App.closestBeaconForTracking != null)
// {
// App.closestBeaconForTracking.RSSI = (int)eddystone.RSSI;
// }
// }
//}
}
SavedPoint flipPoint = new SavedPoint();
//if(App.discoveredBeaconList.Count > 1)
//{
// try
// {
// if (App.discoveredBeaconList[0].BeaconInstanceID != App.closestBeaconForTracking.instanceID)
// {
// App.discoveredBeaconList.Insert(1, App.discoveredBeaconList[1]);
// App.discoveredBeaconList[0].BeaconInstanceID = App.closestBeaconForTracking.instanceID;
// App.discoveredBeaconList[0].BeaconNameSpaceID = App.closestBeaconForTracking.namespaceID;
// App.discoveredBeaconList[0].BeaconID = App.closestBeaconForTracking.BeaconID;
// App.discoveredBeaconList[0].RSSI = App.closestBeaconForTracking.RSSI;
// }
// }
// catch (Exception ex)
// {
// throw new Exception("Error in App.discoveredBeaconList.Count > 1");
// }
//}
//if(App.discoveredBeaconList.Count > 1)
//{
// if(App.discoveredBeaconList[0].RSSI > App.closestBeaconForTracking.RSSI)
// {
// App.closestBeaconForTracking.instanceID = App.discoveredBeaconList[0].BeaconInstanceID;
// App.closestBeaconForTracking.namespaceID = App.discoveredBeaconList[0].BeaconNameSpaceID;
// App.closestBeaconForTracking.RSSI = App.discoveredBeaconList[0].RSSI;
// App.closestBeaconForTracking.truckDesc = App.discoveredBeaconList[0].BeaconTruckDesc;
// }
//}
App.singleOutputValue += eddystone.EddystoneUID.InstanceID + " " + eddystone.RSSI.Int32Value + "; ";
}
if (App.discoveredBeaconList.Count > 0)
{
SavedPoint topBeacon = App.discoveredBeaconList.OrderByDescending(c => c.RSSI).First();
MapApp.Beacon convertedBeacon = new MapApp.Beacon();
convertedBeacon.RSSI = topBeacon.RSSI;
convertedBeacon.Name = topBeacon.BeaconName;
convertedBeacon.namespaceID = topBeacon.BeaconNameSpaceID;
convertedBeacon.instanceID = topBeacon.BeaconInstanceID;
convertedBeacon.BeaconID = topBeacon.BeaconID;
convertedBeacon.truckDesc = topBeacon.BeaconTruckDesc;
App.closestBeaconForTracking = convertedBeacon;
}
if (App.closestBeaconForTracking != null)
{
Console.WriteLine("Selected Beacon: " + App.closestBeaconForTracking.instanceID + " RSSI: " + App.closestBeaconForTracking.RSSI);
MapApp.Beacon beacon = App.Database.GetBeaconByID(App.closestBeaconForTracking.instanceID, App.closestBeaconForTracking.namespaceID);
if(!string.IsNullOrWhiteSpace(beacon.truckDesc))
{
App.catchTruckDesc = beacon.truckDesc;
//Insights.Identify(App.catchTruckDesc);
}
}
else
{
Console.WriteLine("Selected Beacon: no beacon selected");
}
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("------------------------------------------------------------------------");
Console.WriteLine("");
//if (App.closestBeaconForTracking != null && !string.IsNullOrWhiteSpace(App.closestBeaconForTracking.instanceID))
//{
// App.singleOutputValue = "Beacon found at: " + DateTime.Now + Environment.NewLine + App.closestBeaconForTracking.instanceID + " " + App.closestBeaconForTracking.RSSI;
//}
MessagingCenter.Send<App>(App.instance, "singleOutput");
MessagingCenter.Send<App>(App.instance, "UpdateStartText");
MessagingCenter.Send<App>(App.instance, "Output");
}
catch (Exception ex)
{
if (string.IsNullOrWhiteSpace(App.catchFieldDesc))
{
App.catchFieldDesc = "Null";
}
if (string.IsNullOrWhiteSpace(App.catchTruckDesc))
{
App.catchTruckDesc = "Null";
}
Insights.Report(ex, new Dictionary<string, string>() { { "DidDiscoverEddystone", ex.StackTrace }, { "Field Description", App.catchFieldDesc }, { "Truck Description", App.catchTruckDesc } }, Insights.Severity.Critical);
}
}
I have done some searching on the internet, but I have not found anything that would be relevant to my scenario. I'm sure there is an error with my code, but I do not fully understand this error.
I have read that this error can be caused by the Garbage Collector collecting the object.
What exactly does this error mean and what can I look at to attempt a fix?
Thanks!

Input string was not in the correct format with Entity Framework

I'm getting the following exception:
"Input string was not in the correct format."
I'm taking a Json response which is comma delimited and storing it in a database. I'm not sure what is wrong.
Here is the code:
foreach (string s in skaters)
{
skaterData = s.Split(stringSeparator2, StringSplitOptions.None);
Console.WriteLine(skaterData[0] + " " + skaterData[1] + " " + skaterData[2] + " " + skaterData[3] + " " + skaterData[4] + " " + skaterData[5] +
" " + skaterData[6] + " " + skaterData[7] + " " + skaterData[8] + " " + skaterData[9] + " " + skaterData[10] + " " + skaterData[11] + " " + skaterData[12]
+ " " + skaterData[13] + " " + skaterData[14] + " " + skaterData[15]);
try
{
using (var _temp_Player = new FetcherEntities())
{
//int validPlayer;
//int validTeam;
//Skater_Season existingPlayer = _temp_Player.Skater_Season.FirstOrDefault(x => x.player_id == Convert.ToInt32(skaterData[1]) && x.team_id = Convert.ToInt32(skaterData[2]));
// if (existingPlayer != null)
// {
// Console.WriteLine("Existing player: " + existingPlayer.NAME);
// }
// else
// {
_temp_Player.Skater_Season.Add(new Skater_Season
{
player_id = Int32.Parse(skaterData[0]), //stuck here
team_id = Int32.Parse(team),
season_id = season,
Number = Int32.Parse(skaterData[1]),
POS = skaterData[2],
NAME = skaterData[3],
GP = Int32.Parse(skaterData[4]),
G = Int32.Parse(skaterData[5]),
A = Int32.Parse(skaterData[6]),
P = Int32.Parse(skaterData[7]),
plusminus = Int32.Parse(skaterData[8]),
PIM = Int32.Parse(skaterData[9]),
S = Int32.Parse(skaterData[10]),
TOIG = skaterData[11],
PP = Int32.Parse(skaterData[12]),
SH = Int32.Parse(skaterData[13]),
GWG = Int32.Parse(skaterData[14]),
OT = Int32.Parse(skaterData[15])
});
try
{
_temp_Player.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e);
}
}
}
catch (DbEntityValidationException forwardDB)
{
foreach (DbEntityValidationResult entityError in forwardDB.EntityValidationErrors)
{
foreach (DbValidationError error in entityError.ValidationErrors)
{
Console.WriteLine("Error Name: {0} : Message: {1}", error.PropertyName, error.ErrorMessage);
return false;
}
}
}
}
Also I've attached some screen shots of what the data looks like.
Its hard to tell you exactly where the error is but that message is being thrown by one of the Int32.Parse methods receiving data that it cant parse.
The best solution is to use TryParse which allows you to gracefully continue if a problem occurs.

WPF mvvm background worker UI not updated

I'm using the BusyIndicator in my program, the purpose is to show a busy indicator on the view, while the viewModel is loading data from the database.
*Note: before I added the backgroundworker everything worked perfectly.
My program is build in this way:
I have a view that contains:
<NetworkUI:NetworkView
x:Name="networkControl"
NodesSource="{Binding Network.Nodes}"
ConnectionsSource="{Binding Path=Network.Connections}"
MouseDown="networkControl_MouseDown"
MouseUp="networkControl_MouseUp"
MouseMove="networkControl_MouseMove"
/>
Where Network.Nodes and Network.Connections are my problem (I need to see them and I don't)
They are binded to the viewModel called mainWindowViewModel, the main method for getting data from Database called ShowSystem:
public void ShowSystem(bool update)
{
List<String> interfacesForFlow = new List<String>();
#region CreateNetworkClasses
MethodInfo getInterfacesWithGuidToFlow = dbType.GetMethod("getInterfacesWithGuidToFlow");
#endregion
MainNet = Common.Model.Network.getNetwork();
Debug.WriteLine("MainNet.Systems.Count = " + MainNet.Systems.Count);
if (MainNet.Systems.Count == 0)
update = true;
List<String> systemNames = new List<string>();
if (update)
{
if(MainNet.Systems.Count > 0)
MainNet.Systems.Clear();
if (this.Network.Nodes.Count > 0)
{
this.Network.Nodes.Clear();
this.Network.Connections.Clear();
}
try
{
systemNames = (List<String>)getAllSystemMethod.Invoke(sqlDB, null);
Debug.WriteLine("Success getAllSystemMethod");
}
catch (Exception ex)
{
logger.addMessage("Error in getAllSystemMethod: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getAllSystemMethod: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
#region CreateSystems
foreach (var sysName in systemNames)
{
#region Intializating
ObservableCollection<Common.Model.Enum> enums = new ObservableCollection<Common.Model.Enum>();
ObservableCollection<Common.Model.Struct> structs = new ObservableCollection<Common.Model.Struct>();
ObservableCollection<Common.Model.Interface> interfaces = new ObservableCollection<Common.Model.Interface>();
//List<Model.Enum> enums = new List<Model.Enum>();
//List<Model.Struct> structs = new List<Model.Struct>();
//List<Model.Interface> interfaces = new List<Model.Interface>();
int systemId = -1;
Object[] getSystemIdParams = new Object[1];
getSystemIdParams[0] = sysName;
try
{
systemId = (int)getSystemId.Invoke(sqlDB, getSystemIdParams);
Debug.WriteLine("Success getSystemId systemId = " + systemId);
}
catch (Exception ex)
{
logger.addMessage("Error in getSystemId: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSystemId: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
List<int> sysEnumsIds = new List<int>();
List<int> sysStructsIds = new List<int>();
List<int> sysInterfacesIds = new List<int>();
Object[] getSysEnumsIdParams = new Object[1];
getSysEnumsIdParams[0] = systemId;
try
{
sysEnumsIds = (List<int>)getSysEnumsId.Invoke(sqlDB, getSysEnumsIdParams); //return List<int> all system Enums ids
if (sysEnumsIds.Count > 0)
Debug.WriteLine("Success getSysEnumsId first count is " + sysEnumsIds.Count);
else
Debug.WriteLine("success getSysEnumsId but no ids found");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysEnumsId: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysEnumsId: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Object[] getSysStructsIdParams = new Object[1];
getSysStructsIdParams[0] = systemId;
try
{
sysStructsIds = (List<int>)getSysStructsId.Invoke(sqlDB, getSysStructsIdParams);
if (sysStructsIds.Count > 0)
Debug.WriteLine("success getSysStructsId count = " + sysStructsIds.Count);
else
Debug.WriteLine("success getSysStructsId but no ids found");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysStructsId: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysStructsId: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Object[] getSysInterfacesIdParams = new Object[1];
getSysInterfacesIdParams[0] = systemId;
try
{
sysInterfacesIds = (List<int>)getSysInterfacesId.Invoke(sqlDB, getSysInterfacesIdParams);
if (sysInterfacesIds.Count > 0)
Debug.WriteLine("Success getSysInterfacesId count = " + sysInterfacesIds.Count);
else
Debug.WriteLine("success getSysInterfacesId but no ids found");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysInterfacesId: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysInterfacesId: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
#endregion
#region GetInterfaces
foreach (var #interface in sysInterfacesIds) //get interface
{
ObservableCollection<Common.Model.Message> messages = new ObservableCollection<Common.Model.Message>();
ObservableCollection<Common.Model.Definition> definitions = new ObservableCollection<Common.Model.Definition>();
ObservableCollection<Common.Model.Include> includes = new ObservableCollection<Common.Model.Include>();
List<int> includesIds = new List<int>();
List<int> definitionsIds = new List<int>();
List<int> messagesIds = new List<int>();
#region getIncludes
Object[] getIncludesIdsParams = new object[1];
getIncludesIdsParams[0] = #interface;
try
{
includesIds = (List<int>)getIncludesIds.Invoke(sqlDB, getIncludesIdsParams);
Debug.WriteLine("Success getIncludesIds " + includesIds.Count);
}
catch (Exception ex)
{
logger.addMessage("Error in getIncludesIds: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getIncludesIds: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
foreach (var id in includesIds)
{
Object[] getIncludeParams = new object[1];
getIncludeParams[0] = id;
string includeName = "";
try
{
includeName = (string)getInclude.Invoke(sqlDB, getIncludeParams);
Debug.WriteLine("Success get include name = " + includeName);
}
catch (Exception ex)
{
logger.addMessage("Error in getInclude " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getInclude " + ex.Message + " Inner: " + ex.InnerException.Message);
}
includes.Add(new Common.Model.Include(includeName));
}
#endregion
#region getdefinitions
Object[] getdefinitionsIdsParams = new object[1];
getdefinitionsIdsParams[0] = #interface;
try
{
definitionsIds = (List<int>)getDefinitionsIds.Invoke(sqlDB, getdefinitionsIdsParams);
Debug.WriteLine("Success getDefinitionsIds " + definitionsIds.Count);
}
catch (Exception ex)
{
logger.addMessage("Error in getDefinitionsIds: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getDefinitionsIds: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
foreach (var id in definitionsIds)
{
List<Object> definition = new List<object>();
Object[] getDefinitionParams = new object[1];
getDefinitionParams[0] = id;
string includeName = "";
try
{
definition = (List<Object>)getDefinition.Invoke(sqlDB, getDefinitionParams);
Debug.WriteLine("Success getDefinisions " + definition[0]);
}
catch (Exception ex)
{
logger.addMessage("Error in getInclude " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getInclude " + ex.Message + " Inner: " + ex.InnerException.Message);
}
definitions.Add(new Common.Model.Definition(Convert.ToString(definition[0]), Convert.ToInt32(definition[1])));
}
#endregion
Object[] getInterfaceFromIdParam = new Object[1];
getInterfaceFromIdParam[0] = #interface;
List<Object> tempInterface = new List<object>();
try
{
tempInterface = (List<Object>)getInterfaceFromId.Invoke(sqlDB, getInterfaceFromIdParam);
Debug.WriteLine("Success getInterfaceFromId " + tempInterface.Count);
}
catch (Exception ex)
{
logger.addMessage("Error in getInterfaceFromId : " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getInterfaceFromId : " + ex.Message + " Inner: " + ex.InnerException.Message);
}
interfaces.Add(new Common.Model.Interface(messages, definitions, includes, Convert.ToString(tempInterface[0]), Convert.ToString(tempInterface[1]), Convert.ToInt32(tempInterface[2]), Convert.ToInt32(tempInterface[3]), Convert.ToBoolean(tempInterface[4])));
Debug.WriteLine("Success adding new interface: " + interfaces.Last().Name);
}
#endregion
#region InputOutputNumber
List<int> inputs = new List<int>();
List<int> outputs = new List<int>();
int inputCount = 0;
int outputCount = 0;
Object[] getSysInputNumParams = new Object[1];
getSysInputNumParams[0] = systemId;
try
{
inputs = (List<int>)getSysInputs.Invoke(sqlDB, getSysInputNumParams);
if (inputs != null)
{
inputCount = inputs.Count;
Debug.WriteLine("Success getSysInputNum inputs = " + inputCount);
}
else
Debug.WriteLine("Success getSysInputNum inputs = 0");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysInputNum: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysInputNum: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Object[] getSysOutputNumParams = new Object[1];
getSysOutputNumParams[0] = systemId;
try
{
outputs = (List<int>)getSysOutputs.Invoke(sqlDB, getSysOutputNumParams);
if (outputs != null)
{
outputCount = outputs.Count;
Debug.WriteLine("Success getSysOutputNum outputs = " + outputCount);
}
else
Debug.WriteLine("Success getSysOutputNum outputs = 0");
}
catch (Exception ex)
{
logger.addMessage("Error in getSysOutputNum: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSysOutputNum: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
#endregion
Common.Model.System system = null;
try
{
system = new Common.Model.System(interfaces, enums, structs, sysName, inputCount, outputCount, inputs, outputs);
Debug.WriteLine("Success adding new system");
}
catch (Exception ex)
{
logger.addMessage("Error in creating new system: " + ex.Message);
Debug.WriteLine("Error in creating new system: " + ex.Message);
}
MainNet.Systems.Add(system);
Debug.WriteLine("Done! you now have a new system with: " + interfaces.Count + " interfaces And " + enums.Count + " Enums and " + structs.Count + " Structs, The name is: " + sysName + " numOfInput: " + inputCount + " numOfOutput: " + outputCount);
#endregion
}
#endregion
}
#region addNodesToUi
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ));
try
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ));
Debug.WriteLine("Success creating new nodeViewModel");
}
catch (Exception ex)
{
logger.addMessage("Error in creating new nodeViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in creating new nodeViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
}
int width = 0;
int height = 0;
foreach (var system in MainNet.Systems)
{
Debug.WriteLine("inside Foreach in system: " + system.Name + " interface " + system.Interfaces.Count + " structs " + system.Structs.Count);
if (nodes == null)
Debug.WriteLine("FUUUCCKKKK!");
try
{
Debug.WriteLine("Before add node");
try
{
Debug.WriteLine("trying to add: " + system.Name + " " + system.InputNum + " " + system.OutputNum + " " + system.Interfaces.Count + " " + system.Enums.Count + " " + system.Structs.Count);
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => nodes.Add(CreateNode(system.Name, new Point(width, height), false, system.InputNum, system.OutputNum, system.Interfaces, system.Enums, system.Structs, update))));
}
catch (Exception ex)
{
logger.addMessage("Error adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Debug.WriteLine("Success adding new node to list");
}
catch (Exception ex)
{
logger.addMessage("Error in adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in adding new node to list " + ex.Message + " Inner: " + ex.InnerException.Message);
}
width += 150;
if (width >= 700)
{
width = 0;
height += 100;
}
}
if (MainWindow.IsFlow)
{
Object[] getInterfacesWithGuidToFlowParam = new Object[1];
getInterfacesWithGuidToFlowParam[0] = MainWindow.GuidToFlow;
try
{
interfacesForFlow = (List<String>)getInterfacesWithGuidToFlow.Invoke(sqlDB, getInterfacesWithGuidToFlowParam);
Debug.WriteLine("Success getInterfacesWithGuidToFlow " + interfacesForFlow.Count);
}
catch (Exception ex)
{
logger.addMessage("Error in getInterfacesWithGuidToFlow : " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getInterfacesWithGuidToFlow : " + ex.Message + " Inner: " + ex.InnerException.Message);
}
}
foreach (var system in MainNet.Systems)
{
if (system.OutputNum > 0) //this system has an output connector
{
int i = 0;
foreach (var outId in system.Outputs) //loop throw all systems ids that current system is connected to
{
Debug.WriteLine("out id = " + outId);
ConnectionViewModel connection = null;
try
{
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection = new ConnectionViewModel()));
Debug.Write("Success creating new ConnectionViewModel");
}
catch (Exception ex)
{
logger.addMessage("Error in creating new ConnectionViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in creating new ConnectionViewModel " + ex.Message + " Inner: " + ex.InnerException.Message);
}
Object[] getSystemNameParams = new Object[1];
getSystemNameParams[0] = outId;
string destSystemName = "";
try
{
destSystemName = (String)getSystemName.Invoke(sqlDB, getSystemNameParams);
}
catch (Exception ex)
{
logger.addMessage("Error in getSystemName: " + ex.Message + " Inner: " + ex.InnerException.Message);
Debug.WriteLine("Error in getSystemName: " + ex.Message + " Inner: " + ex.InnerException.Message);
}
NodeViewModel sourceItem = null;
NodeViewModel destItem = null;
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => sourceItem = nodes.Find(x => x.Name == system.Name)));
//int sourceId = nodes.FindIndex(sourceItem);
Debug.Write("Success creating new sourceItem");
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => destItem = nodes.Find(x => x.Name == destSystemName)));
Debug.Write("Success creating new destItem");
try
{
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => destItem.InputSystems.Add(sourceItem.Name)));
}
catch (Exception ex)
{
logger.addMessage("Error adding input system: " + ex.Message);
Debug.Write("Error adding input system: " + ex.Message);
}
try
{
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => sourceItem.OutputSystems.Add(destItem.Name)));
}
catch (Exception ex)
{
logger.addMessage("Error adding OutputSystems: " + ex.Message);
Debug.Write("Error adding OutputSystems: " + ex.Message);
}
Debug.Write("Success bah");
//int destId = nodes.FindIndex(destItem);
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.SourceConnector = sourceItem.OutputConnectors[i++]));
Debug.Write("Success bah");
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.DestConnector = destItem.InputConnectors[destItem.InputConnectors.Count - 1]));
Debug.Write("Success bah");
// Add the connection to the view-model.
//
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.Type = ConnectionViewModel.ConnectorType.REGULAR));
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => this.Network.Connections.Add(connection)));
//Debug.Write("Success bah");
if (MainWindow.IsFlow)
{
Debug.WriteLine("inside IsFlow!");
foreach (var #interface in interfacesForFlow)
{
String[] systems = #interface.Split('_');
Debug.WriteLine("Flow from: " + systems[0] + " To " + systems[1]);
if(systems[0].Equals(sourceItem.Name) && systems[1].Equals(destItem.Name))
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => connection.Type = ConnectionViewModel.ConnectorType.FLOW));
}
}
}
}
}
#endregion
}
And this method is being called from the backgroundWorker DoWork method, these all the backgroundWorker references:
public MainWindowViewModel()
{
//
// Create a network, the root of the view-model.
//
Network = new NetworkViewModel();
nodes = new List<NodeViewModel>();
//ShowSystem(false);
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync(false);
//create networkt according to classes created
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => this.IsBusy = false));
this.IsBusy = false;
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => OnPropertyChanged("Network")));
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
//Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ));
this.BusyContent = "Please Wait...";
this.IsBusy = true;
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => ShowSystem((bool)e.Argument)));
}
You have not implemented your BackgroundWorker correctly, despite me already providing you with a link to see how it should be implemented in the comments:
Progress Bar update from Background worker stalling
You're not even calling your ShowSystem method from the BackgroundWorker, so how do you expect to get any data?:
void bw_DoWork(object sender, DoWorkEventArgs e)
{
//You should only update UI properties from here using Dispatcher.CurrentDispatcher
this.BusyContent = "Please Wait...";
this.IsBusy = true;
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() => OnPropertyChanged("Network")));
//This runs on the background thread so this is where you do long running process
ShowSystem(false);
}
You clearly haven't learned how to use a BackgroundWorker yet, so that is what you should be doing, rather than coming here and asking duplicate questions. I already gave you a link to one example of the correct implementation of a BackgroundWorker and you can find another in the BackgroundWorker Class page on MSDN.
I trust that will be enough to get you going again.
Do the UI work in the UI thread, using the dispatcher. See here for more information. So basically, anything that has something to do with a UI control needs to be dispatched to the UI thread.
You have to invoke method in main thread from doWork which is running in separate thread in order to update UI.
I'd suggest to have a look at http://msdn.microsoft.com/en-us/library/dd460693(v=vs.110).aspx which is available in .NET4 and above. (Have a look at Task specifically)

Categories

Resources