Max Young
Max Young

Reputation: 1662

WPF C# application will freeze my whole computer ever 2-3 times I run it

I put a lot of information in this issue because I have no idea what will be relavent

Issue:
I am having an issue with a program I am working on where when running it, it will freeze my whole computer and return no error (I am completely incapable of doing anything CTRL+ALT+DEL doesn't even work). This program accepts a connection from a android client and atm the android client is not configured correctly so the connection is being rejected.

Question:
How can I stop my program from freezing my entire machine?

Conjecture:
I have a few theories as to what is going on but no idea how to fix them. I have read that this may have something to do with me running a single threaded process inside my async worker but I am not sure that the socket is a single threaded process. Also I am not entirely sure how I am supposed to deal with exceptions in a backgroundworker so I just let it fall back to the RunWorkerCompletedEventArgs then retrieve the error message from there.

What I have tried:
- I tried putting try catches every where then removing try catches nothing seems to be able to capture this error
- I checked my systems event log and nothing is showing up except my restarts after my computer freezes
- I have attempted to isolate the issue but it can literally happen at any point from the program starting till when I attempt to connect

Setup:
I am running the program out of visual studio 2012 professional on a windows 8 pro machine. The computer I am on has a i7-3770K 3.50GHz and 32GB of ram. The application that is attempting to make a connection to mine is a Android application and the credentials are incorrect when it is attempting to connect. Visual Studio is running off my main hard drive and building the project on another drive.

Closing:
With all that said would some one please be willing to help me? If you need any more information I will be happy to provide it, please ask.

Main Method:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows;
 using System.Windows.Controls;
 using System.Windows.Data;
 using System.Windows.Documents;
 using System.Windows.Input;
 using System.Windows.Media;
 using System.Windows.Media.Imaging;
 using System.Windows.Navigation;
 using System.Windows.Shapes;
 using System.ComponentModel;

namespace Server
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class SourceServer : Window
{
    private BackgroundWorker worker = new BackgroundWorker();

    public SourceServer()
    {
        InitializeComponent();

        StartListeningForConnections();
    }

    private void StartListeningForConnections()
    {

        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        worker.WorkerReportsProgress = true;

        if (worker.IsBusy != true)
        {
            worker.RunWorkerAsync();
        }
    }

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        worker.ReportProgress(0, "Source server version 0.0.0.1ib started");
        LoginServer oLoginServer = new LoginServer();
        oLoginServer.StartListening(worker);

    }

    private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        try
        {
            lvOutput.Items.Add(e.UserState.ToString());
        }
        catch (Exception exception)
        {
            lvOutput.Items.Add(exception.StackTrace);
        }
    }

    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            System.IO.File.WriteAllText(Environment.CurrentDirectory + @"\log.txt", e.Error.StackTrace + " /n " + e.Error.Message);
        }
        else
        {
            MessageBox.Show("Error was null");
        }
        worker.Dispose();
    }
}
}

SSL Socket Connection:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Threading;
 using System.Net;
 using System.Net.Sockets;
 using System.Windows;
 using System.Windows.Controls;
 using System.ComponentModel;
 using System.Net.Security;
 using System.Security.Cryptography.X509Certificates;
 using MySql.Data.MySqlClient;
 using System.IO;

namespace Server
{
public class LoginServer
{
    // Incoming data from the client.
    public static string data = null;
    public static X509Certificate serverCertificate = null;

    public delegate void UpdateListView(ListView oOutput);

    public void StartListening(BackgroundWorker worker)
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[1];

        serverCertificate = X509Certificate.CreateFromCertFile(@"server.crt");
        TcpListener oServer = new TcpListener(ipAddress, 12345);


        // Bind the socket to the local endpoint and 
        // listen for incoming connections.

        // Start listening for connections.
        while (true)
        {
            Thread.Sleep(100);
            worker.ReportProgress(0, "Waiting for connection....");

            // Program is suspended while waiting for an incoming connection.
            //Socket handler = listener.Accept();
            oServer.Start();
            TcpClient oClient = oServer.AcceptTcpClient();
            Stream oStream = oClient.GetStream();
            SslStream oSSLStream = new SslStream(oStream);

            data = null;

            // An incoming connection needs to be processed.
            string sUsername = "place holder";
            string sPassword = "place holder";

            while (true)
            {
                bytes = new byte[1024];
                int bytesRec = oSSLStream.Read(bytes, 0, bytes.Length);
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

                string[] sCredentials = data.Split("|".ToCharArray()[0]);

                sUsername = sCredentials[0];
                sPassword = sCredentials[1];

                if (data.IndexOf("<EOF>") > -1)
                {
                    break;
                }
            }

            // Show the data on the console.
            worker.ReportProgress(0, "Connection Recieved : ");
            worker.ReportProgress(0, "Username: " + sUsername);
            worker.ReportProgress(0, "Password: " + sPassword);
            worker.ReportProgress(0, "");

            // Echo the data back to the client.
            byte[] msg;
            if (sUsername.Equals("test") && sPassword.Equals("test"))
            {
                msg = Encoding.ASCII.GetBytes("approved<EOF>\n");
                worker.ReportProgress(0, "approved");
                oSSLStream.Write(msg, 0, msg.Length);
            }
            else
            {
                msg = Encoding.ASCII.GetBytes("rejected<EOF>\n");
                worker.ReportProgress(0, "rejected");
                oSSLStream.Write(msg, 0, msg.Length);
            }
        }
    }

    public void VerifyUser()
    {

    }
}
}

Upvotes: 4

Views: 1774

Answers (2)

Simon_Weaver
Simon_Weaver

Reputation: 146198

I've had some hanging problems on Windows 8 that I never saw on Windows 7 (with VS2012). As you experienced it worked fine the first time but only locked up Visual Studio (and not my whole machine) and I had to force quit.

The Visual Studio 2012 Update 4 (which focuses on bug fixes and compatibility) seemed to fix it, although I didn't scientifically test this.

Note: As of 9/1/13 this is only the RC2 version so please check for newer versions, and edit this answer when RTM happens.

Upvotes: 0

DigitalJedi805
DigitalJedi805

Reputation: 1460

While I don't see any reason for this to lock up your entire computer, I do see a couple of reasons for the application to potentially hang...

Your while loop inside of your SSL server will never break unless your client writes

'<EOF>'
to the stream; which you would have to force it to do. I would likely do something similar to this:

while(( bytesRec = oSSLStream.Read(bytes,0,bytes.Length)) > 0 )
{
    // Compare input & break
}

-- The while loop you have now ( without a thread sleep ) will consume all of your systems resources waiting for ... something that may never occur.

In a related issue - I note that your 'DoWork' method launches the listener - but does not start a new thread for this listener. This means that the listener is running inside of your interface thread - which will cause the interface ( and potentially more... ) to hang until the process is completed - which as stated, may never happen.

... Ahem... This last paragraph may be incorrect - you are running an async worker, so I may be incorrect in my second assessment.

Cheers, hope this is helpful.

Upvotes: 2

Related Questions