0
    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.IO.Ports;
using System.Threading;
using System.Windows.Threading;
using System.Data.SQLite;
namespace Datalogging
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public class ThreadExample
    {
        public static void ThreadJob()
        {
            string dBConnectionString = @"Data Source = C:\Users\johnmark\Documents\Visual Studio 2012\Projects\SerialTrial\SerialTrial\bin\Debug\employee.sqlite;";
            SQLiteConnection sqliteCon = new SQLiteConnection(dBConnectionString);
            //open connection to database
            try
            {
                sqliteCon.Open();
                SQLiteCommand createCommand = new SQLiteCommand("Select empID from EmployeeList", sqliteCon);
                SQLiteDataReader reader;
                reader = createCommand.ExecuteReader();
                //richtextbox2.Document.Blocks.Clear();
                while (reader.Read())
                {
                    string Text = (String.Format("{0}", Object.Equals(definition.buffering, reader.GetValue(0))));
                    if (Convert.ToBoolean(Text))
                    {
                        Console.WriteLine(Text);

                    }
                }
                sqliteCon.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
    public partial class MainWindow : Window
    {

        //string received_data;
        //Thread readThread = new Thread(Read);
        FlowDocument mcFlowDoc = new FlowDocument();
        Paragraph para = new Paragraph();
        SerialPort serial = new SerialPort();

        public MainWindow()
        {
            InitializeComponent();
            combobox1.Items.Insert(0, "Select Port");
            combobox1.SelectedIndex = 0;
            string[] ports = null;
            ports = SerialPort.GetPortNames();
            // Display each port name to the console. 
            int c = ports.Count();
            for (int i = 1; i <= c; i++)
            {
                if (!combobox1.Items.Contains(ports[i - 1]))
                {
                    combobox1.Items.Add(ports[i - 1]);
                }
            }
        }
        private void combobox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if ((string)button2.Content == "Connect")
                {
                    string myItem = combobox1.SelectedItem.ToString();
                    if (myItem == "Select Port")
                    {
                        MessageBox.Show("Select Port");
                    }
                    else
                    {
                        serial.PortName = myItem;
                        serial.Open();
                        button2.Content = "Disconnect";
                        textbox2.Text = "Serial Port Opened";
                        serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
                    }
                }
                else
                {
                    serial.Close();
                    button2.Content = "Connect";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        #region Receiving
        public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int bytes = serial.BytesToRead;
            byte[] buffer = new byte[bytes];
            serial.Read(buffer, 0, bytes);
            foreach (var item in buffer)
            {
                Console.Write(item.ToString());
            }
            definition.buffering = BitConverter.ToInt64(buffer, 0);
            Console.WriteLine();
            Console.WriteLine(definition.buffering);
            Console.WriteLine();
            Thread thread = new Thread(new ThreadStart(ThreadExample.ThreadJob));
            thread.Start();
        }
        #endregion
    }
}

Hi. I have this code and I want to put serial.Write() inside this if function:

if (Convert.ToBoolean(Text))
                {
                    Console.WriteLine(Text);
                    //serial.Write();
                }

Can you help me make this serial global so that this error will not exist: The name 'serial' does not exist in the current context?

6
  • It isn't clear what your trying to do here, just an FYI - you cannot write to the serial port from multiple threads at the same time without protecting the read/write with a mutex.
    – asawyer
    Feb 26, 2014 at 16:15
  • yeah. my question is how can I call the serial without any error? Since I need to send a character to the serial port whenever the code enters in that if function
    – iaskyou
    Feb 26, 2014 at 16:16
  • Simple answer (likely wrong): Move SerialPort serial = new SerialPort(); to public static class scope. What does all the SQLite etc have to do with a basic serial port test?
    – user645280
    Feb 26, 2014 at 16:24
  • another problem will arise: an object reference is required for the nonstatic field in threading
    – iaskyou
    Feb 26, 2014 at 16:28
  • 2
    Why bother writing to the sql on a separate thread at all? What exactly are you trying to accomplish here?
    – asawyer
    Feb 26, 2014 at 16:33

1 Answer 1

0

One way to do this is through adding a method to your MainWindow class that calls that method, and passing the window instance to your ThreadJob.

ie. Modify ThreadJob to accept the instance as a parameter:

public static void ThreadJob(MainWindow mainWindow)

Place this in MainWindow somewhere:

public void WriteSerial(string text)
{
    serial.Write(text);
}

Modify your Thread creation to pass the current window instance:

Thread thread = new Thread(new ThreadStart(ThreadExample.ThreadJob(this)));

Now after Console.WriteLine(text) you should be able to write:

mainWindow.SerialWrite(text);

I haven't tested this solution, so it may need some cleaning up. It's probably not the best way to do it, as serial is part of your window instance (you could separate them).

10
  • Putting a WriteSerial() method in definitely seems cleaner, but passing the main window class down to a worker seems messy. Probably it would all be a whole lot better to move all the interesting bits to the worker ThreadExample and let MainWindow call into it (possibly with callbacks) as needed. There could be an internal worker thread in ThreadExample if needed...
    – user645280
    Feb 26, 2014 at 16:37
  • As I previously mentioned, you cannot read and write to a serial port from multiple threads. It's like Ghostbusters - Don't cross the streams. Something like this might satisfy the compiler, but you'll introduce worse, more subtle problems.
    – asawyer
    Feb 26, 2014 at 16:46
  • @ebyrob: I agree, I would write it something like you described.
    – grovesNL
    Feb 26, 2014 at 16:49
  • @asawyer: Agreed, I'm not sure of the purpose of threads here.
    – grovesNL
    Feb 26, 2014 at 16:50
  • sorry I am a newbie and want to try something different. Back to the question, I tried putting the thread in my main window and it works fine. After putting serial.Write(), the error will appear.
    – iaskyou
    Feb 26, 2014 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.