-1

it's the first question I ask so please be tolerant if I do something wrong.

I am writing a software to read data from a serial port a then use it to update the status of a static list of objects. Every data I receive is a communication of a wireless node and it represents its status. I solved the reading part and I am handling the search and update part.

I would like to use the background worker to search the element in the list and then update it, assuring the user a clean and smooth UI. The problem is that I read the bytes through a static function, and from that static function I should call the backgroundworker to perform the task. I read on the dotnetperls guide that "RunWorkerAsync can be called anywhere in your code.", but when I try to call it from the static function, Visual Studio doesn't let me do it.

Can anyone help me?

[edit: code added] This is the extract of my static method:

public static void Add(Byte[] received)
{
    List<byte[]> messages = new List<byte[]>();
    int lastdollars = 0;
    byte[] tempmess = new byte[20];     //The message is 20 digits
    lock (BufferLock)
    {
        //I add the last bytes to the buffer (it's a list of bytes)
        Buffer.AddRange(received);
        if (Buffer.Count < TOTALMESSAGELENGTH) return;
        String temp = Encoding.UTF8.GetString(Buffer.ToArray());
        //I check the buffer to look for complete messages (there are tokens at the start and at the end
        for (int i = 0; i <= (temp.Length - TOTALMESSAGELENGTH + 1); i++)           
        {
            if ((temp.Length > i + TOTALMESSAGELENGTH) &&
                (temp.Substring(i, TOKENLENGTH) == STARTTOKEN) &&
                (temp.Substring((i + TOKENLENGTH + MESSAGELENGTH), TOKENLENGTH) == ENDTOKEN))
            {
                //if I find a message, I put it into the list of messages, I save its position and I continue to look for other messages
                tempmess = Encoding.UTF8.GetBytes(temp.Substring(i, TOTALMESSAGELENGTH));
                messages.Add(tempmess);
                lastdollars = i;
                i += TOTALMESSAGELENGTH - 1;
            }
        }
        if (messages.Count == 0) 
            return;

        //I delete the buffer that I'm using and I need to call the background worker
        Buffer.RemoveRange(0, (lastdollars + TOTALMESSAGELENGTH));
    }
    worker.RunWorkerAsync(messages);    //Error: An object is required for the non-static field, method, or property 'namespace.Form1.worker'
}

I tried both to define manually the backgroundworker with:

private readonly BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;

and adding it through the Toolbox, but the result is the same.

6
  • Could you post a code extract
    – Paul J
    Jan 27, 2014 at 12:03
  • 2
    provide a code snippet so that we can see what/how are you calling this method and then try to help you
    – sameh.q
    Jan 27, 2014 at 12:04
  • Are you getting either of these errors "...is not valid in a static property, static method, or static field initializer" or "An object reference is required for the non-static field, method, or property..."?
    – samar
    Jan 27, 2014 at 12:09
  • 1
    Reading serial port is already occurs in thread , so why not update right there and rise event when finished? What would you do if previous update is not yet finished, when new data is received and parsed? Reading from serial port and writing into a status has nothing to do with UI. Only update it when receiving event.
    – Sinatr
    Jan 27, 2014 at 12:26
  • I'm getting a stream of messages, so I planned to keep the "reading the serial port" thread and the "processing the data" thread separate.
    – Hamma
    Jan 27, 2014 at 12:35

2 Answers 2

1

You cannot access instance variables in static methods. Hence the error. Try and make the BackgroundWorker instance static. Something like the following.

    private readonly static BackgroundWorker worker = new BackgroundWorker();

Not very sure if this will not break any other of your code.

Hope this helps.

0

This doesn't really have anything to do with BackgroundWorker or any specific class. It is just how the C# language works.

You can't access non-static members from a static function. A static function has no implicit this parameter that makes it run against a particular instance of the class. You can run it without ever creating any instances of the class.

This worker

private readonly BackgroundWorker worker = new BackgroundWorker();

will be created once for each instance of the class. But you can call the Add function without having any instances.

For example, this doesn't work for the same reason:

class Adder
{
    public int sum = 0;

    public static void Add(int x)
    {
        sum += x; // can't reference "sum" from static method! 
    }
}

...

Adder.Add(5)

but this works:

class Adder
{
    public int sum = 0;

    public void Add(int x) // no longer static
    {
        sum += x; // this refers to the "sum" variable of this particular instance of Adder
    }
}

...

var adder = new Adder();
adder.Add(5);

and this also works (but differently!):

class Adder
{
    public static int sum = 0; // we made sum static (there is exactly one, instead of a separate sum for each instance)

    public static void Add(int x)
    {
        sum += x; // this refers to the static sum variable
    }
}

...

Adder.Add(5);
1
  • I am aware of the implications of having static variables and methods, but I have never worked with threads; hence, my problem is to structure a thread that is able to handle the incoming messages from the buffer reader (the Add function above).
    – Hamma
    Jan 27, 2014 at 12:48

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.