如何重构在lambda表达式中使用互锁的大型函数?

时间:2019-07-18 22:29:30

标签: c# lambda

我有一个c#函数LongFunction,它类似于:

在此处尝试代码:https://rextester.com/PBBM48190

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Threading;

namespace Rextester
{
    public class Program
    {
        static async Task SomeWork()
        {
            await Task.Delay(100);
            Console.WriteLine("done some work..");
        }

        static void LongFunction()
        {
            // some code here..
            int x = 0;
            // some code here..
            SomeWork().ContinueWith(task => {
                // more code here..
                Interlocked.Increment(ref x);
                // more code here..
            });
            Thread.Sleep(200);
        }

        public static void Main(string[] args)
        {
            LongFunction();
            Console.WriteLine("Done..");
        }
    }
}

如果我尝试将SomeWork().ContinueWith(...的代码移至另一个函数,则必须传递x。但是我找不到正确的方式传递它。

我得到:Cannot use ref or out parameter 'x' inside an anonymous method, lambda expression, or query expression

查看此处:https://rextester.com/OMSN86929

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Threading;

namespace Rextester
{
    public class Program
    {
        static async Task SomeWork()
        {
            await Task.Delay(10);
            Console.WriteLine("done some work..");
        }

        static void LongFunction()
        {
            // some code here..
            int x = 0;
            // some code here..
            foo(ref x);

            Thread.Sleep(200);
            Console.WriteLine("x should be 1 but is {0}", x);
        }

        static void foo(out int x)
        {
            SomeWork().ContinueWith(task => {
                // more code here..
                Interlocked.Increment(ref x);
                // more code here..
            });
            Thread.Sleep(100);
        }

        public static void Main(string[] args)
        {
            LongFunction();
            Console.WriteLine("Done..");
        }
    }
}

0 个答案:

没有答案