从C#中的其他线程使用Invoke访问类成员 [英] Accessing Class members with Invoke from a different thread in C#

查看:666
本文介绍了从C#中的其他线程使用Invoke访问类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:系列的一部分: C# :从其他类访问表单成员

Note: Part of a series: C#: Accessing form members from another class and How to access form objects from another cs file in C#.

你好

想法是在TCP客户端中接收/发送数据包时使用备忘录通知用户.

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";
        }
    }

这就是它的称呼方式

    var form = Form.ActiveForm as Form1;
    if(form != null)
        form.TextValue = "Test asdasd";

但是,由于不安全的线程调用,因此调用代码会引发异常.我在 msdn ,但我似乎无法获得他们在此使用的方法.

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";
        }
    }

错误:

参数"1":无法从方法组"转换为"System.Delegate"

Argument '1': cannot convert from 'method group' to 'System.Delegate'

参数"2":无法从字符串"转换为对象[]"

Argument '2': cannot convert from 'string' to 'object[]'

基本上,我正在尝试使用Invoke从另一个线程访问备忘录(或更可能是说,向备忘录中添加文本).我以前从未使用过它,也许这就是为什么我误解了我的错误.

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.

推荐答案

简单的方法是:

this.Invoke((MethodInvoker)delegate {
    this.Memo.Text += txt + "\n";
});

使用匿名方法内联完成工作.由于您期望在另一个线程上,因此您最好只调用Invoke-即使从UI线程也很安全.

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.

这篇关于从C#中的其他线程使用Invoke访问类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆