Note: Part of a series: C#: Accessing form members from another class and How to access form objects from another cs file in C#.
Hello,
The Idea is to notify the user using the memo when a packet is received/sent in a TCP Client.
After couple of fixes,the most suitable solution seemed to be this one
public string TextValue { set { this.Memo.Text += value + '\n'; } }
That’s how it’s being called
var form = Form.ActiveForm as Form1; if(form != null) form.TextValue = 'Test asdasd';
However,calling the code throws an exception ,because of Unsafe thread call.I found a solution at msdn,but I can’t seem to acquire the method they’ve used there.
This is my remake,which doesn’t work.
private void SetTextMemo(string txt) { if(this.Memo.InvokeRequired) { this.Invoke(SetTextMemo,txt); //error here } else { this.Memo.Text += txt + '\n'; } }
errors:
Argument ‘1’: cannot convert from ‘method group’ to ‘System.Delegate’
Argument ‘2’: cannot convert from ‘string’ to ‘object[]’
Basically,I’m trying to access the Memo(or more likely said,add text to the memo) from another thread using Invoke.I never used it before,maybe that’s why I misunderstand my mistake.
The easy way is:
Which uses an anonymous method to do the job inline. Since you expect to be on another thread, you may as well just call Invoke – it is safe even from the UI thread.