从线程调用带字符串返回类型的函数 [英] Calling a function with string return type from thread

查看:72
本文介绍了从线程调用带字符串返回类型的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我是C#线程的新手,请原谅我如果你觉得我的问题很简单。我们可以在线程中调用一个函数吗?在此先感谢。

Hi guys
I'm new to C# threads so forgive me If you feel my question is very simple.Can we call a function in thread who has parameters in it? Thanks in advance.

推荐答案

是的。正如您在普通UI线程中所做的那样 - 所有代码都在一个线程上运行,因此从哪个线程调用方法并不重要:如果它返回一个字符串,它会在同一个线程上向调用者返回一个字符串。

Yes. Exactly as you would from the "normal" UI thread - all code runs on a thread, so it doesn't matter which thread you call a method from: if it returns a string, it returns a string to the caller on the same thread.
private void button1_Click(object sender, EventArgs e)
    {
    BackgroundWorker work = new BackgroundWorker();
    work.DoWork += new DoWorkEventHandler(work_DoWork);
    work.RunWorkerAsync();
    }

void work_DoWork(object sender, DoWorkEventArgs e)
    {
    Console.WriteLine(GetMyString());
    }
string GetMyString()
    {
    return DateTime.Now.ToString();
    }


看看这里:

多线程程序的参数和返回值(C#和Visual Basic) [ ^ ]

如何:从任务中返回值 [ ^ ]
Have a look here:
Parameters and Return Values for Multithreaded Procedures (C# and Visual Basic)[^]
How to: Return a Value from a Task[^]


这篇关于从线程调用带字符串返回类型的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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