【发布时间】:2021-01-12 17:25:41
【问题描述】:
using System;
using System.Threading;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
public static void Main()
{
// The asynchronous method puts the thread id here.
int threadId;
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// Initiate the asychronous call.
IAsyncResult result = caller.BeginInvoke(3000,
out threadId, null, null);
Thread.Sleep(0);
Console.WriteLine("Main thread {0} does some work.",
Thread.CurrentThread.ManagedThreadId);
// Call EndInvoke to wait for the asynchronous call to complete,
// and to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
}
}
EndInvoke 可能会阻塞调用线程,因为它在异步调用完成之前不会返回。
我将在 API 中实现EndInvoke,以防止用户调用 API 两次。
我是否使用正确的方法来防止同一用户同时调用 API 两次?
【问题讨论】:
-
Begin和End类型方法是较旧的 APM 模型,它主要处理处理异步编程的较旧方法。它与线程安全、锁定或防止某人同时调用一个方法无关。您必须自己使用诸如lock之类的同步原语来实现它 -
@JohnWalker 你能和我们分享一下
AsyncDemo类的定义吗?您的AsyncMethodCaller代表是如何定义的?它们的定义类似于 this 吗? -
这里的实际目标是什么?您是否有要保护的非线程安全 API?如果是这样,一个简单的锁或任务队列会更合适。
-
什么浏览器??这是一个控制台应用程序。没有浏览器。没有任何阻塞,
await等待已经存在的操作完成而不阻塞调用者 -
我怀疑您的真正问题与 BeginInvoke 或任务无关。您认为 BeginInvoke 将是解决方案,所以您问了这个问题。 实际问题是什么?
标签: c# multithreading