我们有一个代码,其中两个锁以不同的方法锁定在同一对象上。这两种方法都可以从不同的线程调用。
这会进入僵局吗?我们应该在两种方法中使用相同的 lock1 吗?
使用两个不同的锁的原因是移除发生在并行运行的各种任务中,但更新列表发生在每隔几秒运行一次的新线程中。
private static Object Lock1 = new Object();
private static Object Lock2 = new Object();
private static List<string> list = new List<string>();
public void Method1()
{
lock(Lock1)
{
//update list
}
}
public void Method2()
{
lock(Lock2)
{
//remove from list
}
}
Run Code Online (Sandbox Code Playgroud)
感谢您的健康讨论,我已更新我的代码以使用 .net 提供的线程安全集合 BlockingCollection。我继续使用 lock1,因为我需要控制列表可以包含的对象数量。我现在已经删除了 lock2,因为线程安全列表不需要它。
我的问题是在什么情况下或在什么情况下最好使用可调用接口而不是简单的单一方法功能接口。
假设我们有一个带有基于任务的事件处理系统的游戏。它每秒循环一个事件队列。每个事件都涉及一名玩家。在什么情况下最好这样做
Consumer<Player> c1 = (player) -> player.sendMessage("hey");
Run Code Online (Sandbox Code Playgroud)
超过
Runnable r1 = () -> player.sendMessage("hey");
Run Code Online (Sandbox Code Playgroud)
刚刚发现这个问题:Java 中 Runnable 和 Callable 接口之间的区别。它解释了有关多线程环境的一些要点,但我所说明的情况涉及单线程环境。那还有关系吗?
这是挂起且永不结束的简单代码段:
public static void Main()
{
using (var cancellationTokenSource = new CancellationTokenSource())
{
Console.CancelKeyPress += (_, __) =>
cancellationTokenSource.Cancel();
while (!cancellationTokenSource.Token.WaitHandle.WaitOne(1000))
{
Console.WriteLine("Still running...");
}
Console.WriteLine("Cancellation is requested. Trying to dispose cancellation token...");
}
Console.WriteLine("Just before close");
}
Run Code Online (Sandbox Code Playgroud)
问题是Just before close线条永远不会被执行。我的第一个想法是“可能是因为 KeyPress 关闭了”所以我用以下方式重写了它:
public static void Main()
{
using (var cancellationTokenSource = new CancellationTokenSource())
{
void Foo(object sender, ConsoleCancelEventArgs consoleCancelEventArgs)
{
cancellationTokenSource.Cancel();
}
Console.CancelKeyPress += Foo;
while (!cancellationTokenSource.Token.WaitHandle.WaitOne(1000))
{
Console.WriteLine("Still running...");
}
Console.WriteLine("Cancellation is requested. Unsubscribing...");
Console.CancelKeyPress -= …Run Code Online (Sandbox Code Playgroud) 我收到以下异常:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at GoogleProducts.Program.<Main>d__0.MoveNext() in C:\Code\test\GoogleProducts\Program.cs:line 60
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at GoogleProducts.Program.<Main>(String[] args)
来源是:
private static async Task Main(string[] args)
{
var queries = new[]
{
"seico watch",
"citizen watch",
"orient watch",
"bulova watch",
"seagull watch",
"glashuette watch"
};
var client = new WebClient();
foreach (var query in queries)
{
var url = …Run Code Online (Sandbox Code Playgroud) 我想取消正在运行的任务(当用户按下退出键时)。当我点击“escape”键 Form_KeyDown 运行但不取消任务时!
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token=new CancellationToken();
private async void Search_Button_ClickAsync(object sender, EventArgs e)
{
token = tokenSource.Token;
await (Task.Factory.StartNew(() =>
{
//...my program
},
token));
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
tokenSource.Cancel();
}
}
Run Code Online (Sandbox Code Playgroud) c# task cancellation cancellationtokensource cancellation-token
我RabbitMq用来处理我在公共汽车上收到的消息。我想知道是否有更好的方法来处理我收到的消息(也许使用async/await模式)
这是我的代码片段
connection = connectionFactory.CreateConnection();
channel = connection.CreateModel();
channel.QueueDeclare(queue: Constants.RabbitListeningQueue,durable: false,exclusive: false,autoDelete: false,arguments: null);
channel.QueueDeclare(queue: Constants.RabbitMqRequestInsertedQueue,durable: false,exclusive: false,autoDelete: false,arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
log.Debug($"[x] Received message :{ea}");
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
var dynamicObject = JObject.Parse(message);
queueMessageHandler.HandleMessage(dynamicObject);
};
Run Code Online (Sandbox Code Playgroud)
将queueMessageHandler实现如下
public class QueueMessageHandler : IQueueMessageHandler
{
private readonly IImportNucleoManager importNucleoManager;
public QueueMessageHandler(IImportNucleoManager importNucleoManager)
{
this.importNucleoManager = importNucleoManager;
}
public void HandleMessage(dynamic message)
{
switch …Run Code Online (Sandbox Code Playgroud) 在什么情况下你会返回 aTask<T>而不async在方法签名中使用?
我在下面的代码中有这样一个方法,但我无法理解发生了什么。
为什么我下面的示例代码没有执行任何await语句?IE。为什么Console.WriteLine("4)");与Console.WriteLine("3)");和return x;从来没有得到执行?
class Program
{
static void Main(string[] args)
{
TestAsync testAsync = new TestAsync();
testAsync.Run();
Console.Read();
}
}
public class TestAsync
{
public async void Run()
{
Task<int> resultTask = GetInt();
Console.WriteLine("2)");
int x = await resultTask;
Console.WriteLine("4)");
}
public async Task<int> GetInt()
{
Task<int> GetIntAfterLongWaitTask = GetIntAfterLongWait();
Console.WriteLine("1)");
int x = await GetIntAfterLongWaitTask;
Console.WriteLine("3)");
return x;
}
public Task<int> GetIntAfterLongWait()
{
Task.Run(() => …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个.WithDelay(seconds);可以在异步方法调用结束时添加的方法。
我得到的问题是先调用 async 方法然后延迟发生,我希望它反过来,不切换调用顺序。
例如,我想要await MyMethod().WithDelay(seconds);而不是await WithDelay(seconds).MyMethod();.
这是我到目前为止所拥有的,它首先调用该方法:
public async static Task<T> WithDelay<T>(this Task<T> task, int delay) {
await Task.Delay(delay);
return await task;
}
Run Code Online (Sandbox Code Playgroud)
我希望延迟首先发生,然后是实际运行的方法。
在使用 async-await 的程序中,我的理解是这样的:
下面的申请是我写的,以检查上述陈述是否正确。
using System;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
DoJob();
var z = 3;
Console.ReadLine();
}
static async Task DoJob()
{
var work1 = new WorkClass();
var work2 = new WorkClass();
while (true)
{
await work1.DoWork(500);
await work2.DoWork(1500);
}
}
}
public class WorkClass
{
public async Task DoWork(int delayMs)
{
var x = 1;
await Task.Delay(delayMs);
var y = 2;
}
} …Run Code Online (Sandbox Code Playgroud) 返回匿名对象的 C# 中异步方法的最佳/正确返回类型是什么?我的方法通过实体框架选择一些数据。我最好的猜测是这样的:
public async Task<object> GetStuff() {
abClass ret = await DoSomethingAsync();
return new { Param1 = ret.a, Param2 = ret.b };
}
Run Code Online (Sandbox Code Playgroud)
但是 Task 实际上是做到这一点的最佳方法,还是有一些 Task 或类似的东西?
task ×10
c# ×9
async-await ×5
asynchronous ×3
.net ×1
cancellation ×1
consumer ×1
java ×1
locking ×1
rabbitmq ×1