我有一个由Task.Run调用的异步方法。当我发送字符串形式参数时
...
{
string objectStr = "SomeData";
...
Task t = Task.Run(async () => Sender(objectStr));
Thread.Sleep(10); /// IF I REMOVE IT, VALUE WILL SAND EMPTY
objectStr = string.Empty;
}
public async static void Sender(string info)
{
/// BODY
}
当然,发送变量引用是错误的。如何在其中发送不变的值?
答案 0 :(得分:0)
要复制字符串,请使用new
运算符传递字符串:
{
string objectStr = "SomeData";
//...
Task t = Task.Run(async () => Sender(new String(objectStr.ToCharArray())));
objectStr = string.Empty;
}
这将创建String
的单独副本。