这是我问的第一个问题,如果我做错了,请耐心等待。从静态方法呼叫BackgroundWorker
我正在写一个软件从串口a读取数据,然后用它来更新静态对象列表的状态。我收到的每个数据都是一个无线节点的通信,它代表了它的状态。我解决了阅读部分,我正在处理搜索和更新部分。
我想使用后台工作人员搜索列表中的元素,然后更新它,确保用户一个干净和平滑的用户界面。问题是我通过静态函数读取字节,并从该静态函数中调用backgroundworker来执行任务。我在dotnetperls指南上看到,“RunWorkerAsync可以在代码中的任何位置调用”,但是当我尝试从静态函数调用它时,Visual Studio不让我这样做。
任何人都可以帮助我吗?
[编辑:添加的代码] 这是我的静态方法的提取物:
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'
}
我尝试都与限定手动BackgroundWorker的:
private readonly BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
并通过工具箱添加它,但结果是一样的。
您能否发布代码提取 –
提供代码片段,以便我们可以看到您将如何调用此方法,然后尝试帮助您 – simsim
您是否收到这些错误之一“...在一个无效的静态属性,静态方法或静态字段初始值设定项“或”非静态字段,方法或属性需要对象引用...“? – samar