Given this code....
public class CalibrationViewModel : ViewModelBase
{
private FileSystemWatcher fsw;
public CalibrationViewModel(Calibration calibration)
{
fsw = new FileSystemWatcher
{
Path = @"C:\Users\user\Desktop\Path\ToFile\Test_1234.txt",
Filter = @"Test_1234.txt",
NotifyFilter = NotifyFilters.LastWrite
};
fsw.Changed += (o, e) =>
{
var lastLine = File.ReadAllLines(e.FullPath).Last();
Dispatcher.BeginInvoke((Action<string>) WriteLineToSamplesCollection, lastLine); //line that cites error
};
}
private void WriteLineToSamplesCollection(string line)
{
// do some work
}
}
Why am I getting the error, 'Cannot access non-static method BeginInvoke in static context'?
I have looked at several other examples on SE and most cite trying to use a field before the object is created as if they were trying to use a non-static field in a static manner, but I don't understand what it is about my code that is invoking the same error.
Lastly, what can I do to fix this specific issue/code?
Update: Fixed title to reflect issue with a 'method' and not a 'property'. I also added that the class implements ViewModelBase.
You have to create instance first. The instance method (method that is not static) cannot be accessed from static context by definition. Show activity on this post. Basically, you can only call non-static methods from objects [instances of a class] rather than the class itself.
Of course, they can but the opposite is not true i.e. you cannot access a non-static member from a static context i.e. static method. The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs.
There is one simple way of solving the non-static variable cannot be referenced from a static context error. Address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context.
In other words, non-static data cannot be used in static methods because there is no well-defined variable to operate on.
If this is WPF, System.Windows.Threading.Dispatcher
does not have a static BeginInvoke()
method.
If you want to call that statically (this is, without having a reference to the Dispatcher instance itself), you may use the static Dispatcher.CurrentDispatcher
property:
Dispatcher.CurrentDispatcher.BeginInvoke(...etc);
Be aware though, that doing this from a background thread will NOT return a reference to the "UI Thread"'s Dispatcher, but instead create a NEW Dispatcher instance associated with the said Background Thread.
A more secure way to access the "UI Thread"'s Dispatcher is via the use of the System.Windows.Application.Current
static property:
Application.Current.Dispatcher.BeginInvoke(...etc);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With