开发者

C# Breaking larger method into two threads

开发者 https://www.devze.com 2023-01-27 23:10 出处:网络
If I have a large method that is composed of two small methods: public int LargeMethod() { int result = 0;

If I have a large method that is composed of two small methods:

public int LargeMethod() 
{ 
int result = 0; 
result += Small开发者_Python百科MethodA(); 
result += SmallMethodB(); 
}

Both small methods block my program for atleast 2 seconds and I believe it will really be better for performance if I let the two methods run in their own threads.

Can you please suggest a programming model?


If you are using .NET 4 you can use tasks

public int LargeMethod()
{
    int result = 0;
    Task<int> t1 = new Task<int>(SmallMethodA);
    Task<int> t2 = new Task<int>(SmallMethodB);
    t1.Start();
    t2.Start();
    result += t1.Result;
    result += t2.Result;
    return result;
}


Read this Task Parallel Library for more information's and here you have solution:

Task<int>[] taskArray = new Task<int>[]
   {
       Task<int>.Factory.StartNew(() => SmallMethodA()),
       Task.Factory.StartNew(() => SmallMethodB()),           
   };

int result = 0;
for (int i = 0; i < taskArray.Length; i++)
{
    result += taskArray[i].Result;
}


CLR2:

  • You can define delegates for the methods, create an instance of the delegate and use the "BeginInvoke/EndInvoke" methods.
  • Use the "ThreadPool" to "EnqueueWorkerItem"
  • Use System.Thread to create a new Thread and start your method on it.

CLR4:

  • Use the task library
  • revert tot CLR2 patterns

Hope this helps,

ps; Your looking at the 'Parallel Block' pattern.


If the operations are short, I would probably put the calls to them into anonymous methods that are executed using the ThreadPool, paired with using the Interlocked class for updating the result variable.


How about Tasks? Untested code below...

Task<int> t1 = new Task<int>(() => return SmallMethodA());
Task<int> t2 = t1.ContinueWith((t) => return t.Result + SmallMethodB());
t1.Start();

Of course you could just wrap up both SmallMethodA and SmallMethodB within a single task. If you're writing to the UI afterwards, be sure to use a ContinueWith task that runs on the current thread context.


I like Albin Sunnanbo's answer (http://stackoverflow.com/questions/4303605/c-breaking-larger-method-into-two-threads/4303662#4303662)

but then with just 1 fork to make it just a bit quicker and less verbose:

public int LargeMethod()
{    
    var t1 = new Task<int>(SmallMethodA);
    t1.Start();
    int result = SmallMethodB();    
    result += t1.Result;    
    return result;
}

Edit even less like this:

public int LargeMethod()
    {    
        var t1 = new Task<int>.Factory.StartNew(SmallMethodA);
        return SmallMethodB() + t1.Result;
    }

GJ

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号