我能想到几种可能性。
解决方案一:使用包装类
using System;
using System.Threading;
namespace Demo
{
internal class Program
{
private static void Main(string[] args)
{
var melody = new Melody { Value = 1 };
var wrapper = new MelodyWrapper { Melody = melody };
Thread melodyThread = new Thread(() => PlayMelody(wrapper));
melodyThread.Start();
melodyThread.Join();
Console.WriteLine(wrapper.Melody.Value);
}
private static void PlayMelody(MelodyWrapper wrapper)
{
Console.WriteLine(wrapper.Melody.Value);
Thread.Sleep(1000);
wrapper.Melody.Value = 2;
}
}
public struct Melody
{
public int Value;
}
public class MelodyWrapper
{
public Melody Melody;
}
}
或者,不使用 Lambda:
using System;
using System.Threading;
namespace Demo
{
internal class Program
{
private static void Main(string[] args)
{
var melody = new Melody { Value = 1 };
var wrapper = new MelodyWrapper { Melody = melody };
Thread melodyThread = new Thread(PlayMelody);
melodyThread.Start(wrapper);
melodyThread.Join();
Console.WriteLine(wrapper.Melody.Value);
}
private static void PlayMelody(object parameter)
{
MelodyWrapper wrapper = (MelodyWrapper)parameter;
Console.WriteLine(wrapper.Melody.Value);
Thread.Sleep(1000);
wrapper.Melody.Value = 2;
}
}
public struct Melody
{
public int Value;
}
public class MelodyWrapper
{
public Melody Melody;
}
}
解决方案二:使用 Delegate 并返回 Melody 的新值
using System;
using System.Threading;
namespace Demo
{
internal class Program
{
private static void Main(string[] args)
{
var melody = new Melody { Value = 1 };
Func<Melody, Melody> play = PlayMelody;
var result = play.BeginInvoke(melody, null, null);
melody = play.EndInvoke(result);
Console.WriteLine(melody.Value);
}
private static Melody PlayMelody(Melody melody)
{
Console.WriteLine(melody.Value);
Thread.Sleep(1000);
melody.Value = 2;
return melody;
}
}
public struct Melody
{
public int Value;
}
}
我个人赞成第二种解决方案。Melody
因为它返回一个新值,所以如果您使用此解决方案,您可以将其设为不可变。
(我首选的解决方案使用Task<Melody>
但您不能使用任务。)