如何从返回类型为c#的不同线程调用相同的方法 [英] How to call same method from different threads with return type c#

查看:57
本文介绍了如何从返回类型为c#的不同线程调用相同的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想从for循环中调用一个方法,并在UI中呈现之前组合返回类型,并且方法调用应该在新线程中,以便我可以减少执行时间。



以下是代码

  private   void  Start_Click( object  sender,EventArgs e)
{
string [] param = { US UK CND};
ArrayList getData = new ArrayList();


for int i = 0 ; i < param.Length; i ++)
{
// 多线程调用
getData.AddRange(GetData(param [i]));
}

// marge all returns
dg.DataSource = getData;

}

private ArrayList GetData( string param)
{
ArrayList returnData = new ArrayList();
for int i = 0 ; i < 10 ; i ++)
{
returnData.Add (param + i.ToString());
}
Thread.Sleep( 3000 );
return returnData;
}

解决方案

我认为你发布的代码只是一个例子。如果是这种情况,一种方法是使用Parallel类。



首先在类级别定义一个对象变量

  object  _lockobject =  new   object (); 



尝试类似以下的内容

  string  [] param = {  US  UK  CND}; 
System.Collections.ArrayList getData = new System.Collections.ArrayList();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

// 顺序执行
watch.Reset();
watch.Start();
for int i = 0 ; i < param.Length; i ++){
getData.AddRange(GetData(param [i]));
}
watch.Stop();
System.Diagnostics.Debug.WriteLine( string .Format( 顺序执行花了{0},watch.Elapsed.ToString()));

// 并行执行
watch.Reset();
watch.Start();
System.Threading.Tasks.Parallel.For( 0 ,param.Length,(i)= > {
System.Collections.ArrayList partialresult;
partialresult = GetData(param [i]);
lock this ._ lockobject){
getData.AddRange(partialresult);
}
});
watch.Stop();
System.Diagnostics.Debug.WriteLine( string .Format( 并行执行{0},watch.Elapsed.ToString()));


使用async& amp;尝试任务并行库(TPL)等待功能。下面的文章解释了最好的...



你可以使用(ContinueWhenAll和ContinueWhenAny)或(WhenAll and WhenAny)



任务并行库和异步等待功能 - 使用模式在简易样本中 [ ^ ]


很抱歉没有回答你的问题;没有什么可以回答的。你需要了解不同的东西:线程,并行,只是基础知识,首先是目的。到目前为止,你没有任何线索 - 请看我对这个问题的评论。我建议从这开始:

https://en.wikipedia.org/wiki/Race_condition [ ^ ],

https://en.wikipedia.org/wiki/Concurrency_control [ ^ ],

https://en.wikipedia.org/wiki/Synchronization_%28computer_science%29 [ ^ ]。



-SA

Hi,

I want to call a method from for loop and combine the return type before presenting in the UI and method calling should in new thread so that I can reduce the execution time.

Below is the code

private void Start_Click(object sender, EventArgs e)
        {
            string[] param = { "US", "UK", "CND" };
            ArrayList getData = new ArrayList();
            

            for (int i = 0; i < param.Length; i++)
            {
                //call in multithread
                getData.AddRange(GetData(param[i])); 
            }

            //marge all returns
            dg.DataSource = getData;
            
        }

        private ArrayList GetData(string param)
        {
            ArrayList returnData = new ArrayList();
            for (int i = 0; i < 10; i++)
            {
                returnData.Add(param + i.ToString());
            }
            Thread.Sleep(3000);
            return returnData;
        }

解决方案

I take it the code you posted is just an example. If that is the case one way would be to use Parallel class.

First define an object variable on the class level

object _lockobject = new object();


And try something like the following

string[] param = { "US", "UK", "CND" };
System.Collections.ArrayList getData = new System.Collections.ArrayList();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

// Sequential execution
watch.Reset();
watch.Start();
for (int i = 0; i < param.Length; i++) {
   getData.AddRange(GetData(param[i]));
}
watch.Stop();
System.Diagnostics.Debug.WriteLine(string.Format("Sequential execution took {0}", watch.Elapsed.ToString()));

// Parallel execution
watch.Reset();
watch.Start();
System.Threading.Tasks.Parallel.For(0, param.Length, (i) => {
   System.Collections.ArrayList partialresult;
   partialresult = GetData(param[i]);
   lock (this._lockobject) {
      getData.AddRange(partialresult);
   }
});
watch.Stop();
System.Diagnostics.Debug.WriteLine(string.Format("Parallel execution took {0}", watch.Elapsed.ToString()));


Try Task Parallel Library (TPL) with async & await functionality. Following article explains the best...

You can use (ContinueWhenAll and ContinueWhenAny) or (WhenAll and WhenAny)

Task Parallel Library and async-await Functionality - Patterns of Usage in Easy Samples[^]


Sorry for not answering your question; there is nothing to answer to. You need to understand different things: threading, parallelism, just the basics, first of all, the purpose. So far, you have no clue — please see my comment to the question. I would advise to start with this:
https://en.wikipedia.org/wiki/Race_condition[^],
https://en.wikipedia.org/wiki/Concurrency_control[^],
https://en.wikipedia.org/wiki/Synchronization_%28computer_science%29[^].

—SA


这篇关于如何从返回类型为c#的不同线程调用相同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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