TALK IS CHEAP, SHOW ME THE CODE.

Introduction to Overlapped I/O#

Overlapped I/O is a Win32 technique where you ask the operating system to transfer data for you and notify you when the transfer is done. It lets your program keep handling other work while I/O is in progress. It’s also known as non-blocking I/O or asynchronous I/O.

Suppose a thread issues an asynchronous I/O request to a device. The request is handed to the device driver, which is responsible for carrying out the actual I/O operation. While the driver waits for the device to respond, the application’s thread is not suspended waiting for the I/O request to complete; it keeps running and does other useful work.

It comes in four flavors of asynchronous I/O, ranging from simple to advanced:

  • Signaled File Handles
  • Signaled Event Objects
  • Asynchronous Procedure Calls (APC)
  • I/O Completion Port (IOCP)

Prerequisites for Using Overlapped I/O#

To access a device asynchronously, we need to call the Win32 CreateFile function and open the device with the FILE_FLAG_OVERLAPPED flag in the dwFlagsAndAttributes parameter. This flag tells the operating system that we want to access the device asynchronously.

Read More

The CLR thread pool#

There is one thread pool per CLR, and it’s shared by all the AppDomains that CLR controls. If a process loads multiple CLRs, each CLR has its own separate thread pool.

When the CLR initializes, the thread pool has no threads in it. Internally, the thread pool maintains a queue of operation requests. When your application wants to perform an asynchronous operation, you call some method that appends an entry to the thread pool’s queue. The thread pool’s code extracts entries from this queue and dispatches each entry to a thread pool thread. If there are no threads in the pool, a new one is created. When a thread pool thread finishes its task, it isn’t destroyed; instead it returns to the pool, goes idle and waits to be assigned a new task.

The thread pool is heuristic: it automatically adjusts how it works based on the current application load and the hardware’s capabilities.

Read More

In this post I summarize how the Win32 API and the C# API map to each other for multithreading. They’re often similar, but there are some differences too.

Threads#

Creating a thread#

When you create a thread, you usually need to specify “what it does”, i.e. supply a function pointer or a delegate.

Win32 uses the CreateThread function to create a thread:

HANDLE CreateThread(
    PSECURITY_ATTRIBUTES pThreadAttributes,
    DWORD dwStackSize,
    PTHREAD_START_ROUTINE pStartAddress,
    PVOID pParameter,
    DWORD dwCreationFlags,
    PDWORD pdwThreadId
)

C# wraps threads up, and you create one with a statement like this:

Thread t = new Thread(()=>{
    Console.WriteLine("Hello,Thread");
});

For the same task, the two implementations look different:

#include <windows.h>

DWORD WINAPI ThreadFunc(LPVOID);

int main()
{
    HANDLE hThread;
    DWORD threadId;
    hThread = CreateThread(NULL, 0, ThreadFunc, 0, 0, &threadId);
    return 0;
}

DWORD WINAPI ThreadFunc(LPVOID p)
{
    int p0 = (int)p;
    printf("Parameter:%d\n", p0);
}
using System;
using System.Threading;

public class Program{
    public static void Main(string[] args)
    {
        Thread t = new Thread(ThreadFunc);
        t.Start(0);
    }
    
    static void ThreadFunc(Object o)
    {
        int p0 = (int)o;
        Console.WriteLine($"Parameter:{p0}");
    }
}

Forcibly terminating a thread#

Every now and then we need to forcibly terminate a thread.

Read More

FAQ notes#

FAQ 01: What’s the difference between cooperative multitasking and preemptive multitasking?#

Cooperative multitasking means the programmer controls how programs share the CPU. Multiple programs have to share the CPU appropriately, and once one program refuses to share and hogs everything, the other programs can’t do anything. In other words, control lies with the programs, not the operating system.

Tip

Windows 1, 2 and 3 were cooperative multitasking operating systems.

Preemptive multitasking means the operating system controls how programs share the CPU, so programmers don’t have to worry about sharing the CPU. In other words, control lies with the operating system, not the programs.

Tip

Unix, VMS, AmigaDOS and others are preemptive operating systems.

FAQ 02: Can I use multiple threads in Win32s?#

No. Win32s is a port of the Win32 API to Windows 3.1, but unfortunately a lot of functionality couldn’t be ported. Win32s supports neither preemptive multitasking nor multithreading.

Read More

When does a type object get loaded onto the Loader heap? And when is the type initializer actually called?

Read More

An AppDomain can be unloaded manually, and sometimes we may want our program to be notified when one or more AppDomains get unloaded.

So how can a program monitor the unloading of an AppDomain?

Exploring All the Event Members of System.AppDomain#

The first thing that came to mind was to check whether the AppDomain class exposes any public event members.

To quickly find out which events exist, I created an AppDomain instance with the static method CreateDomain, then used IntelliSense and filtered by the lightning bolt icon (which stands for events) to get the list right away:

As you can see, there are 9 public event members:

  • DomainUnload : Occurs when an AppDomain is about to be unloaded
  • AssemblyLoad : Occurs when an assembly is loaded
  • AssemblyResolve : Occurs when the resolution of an assembly fails
  • FirstChanceException : Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain
  • ProcessExit : Occurs when the default application domain’s parent process exits
  • ReflectionOnlyAssemblyResolve : Occurs when the resolution of an assembly fails in the reflection-only context
  • ResourceResolve : Occurs when the resolution of a resource fails because the resource is not a valid linked or embedded resource in the assembly
  • TypeResolve : Occurs when the resolution of a type fails
  • UnhandledException : Occurs when an exception is not caught

The very first one happens to be exactly the event I need: DomainUnload.

Read More

How do you draw a shine? I studied how saint11 does it and broke it down a bit.

A shine should be the path of light moving along an object’s reflective surface. The light starts at one point and ends at another, like this:

BasicShine
BasicShine

Of course, to make the shine more visually striking, you can enrich it a bit, like this, by adding a few frames:

ExtraShine
ExtraShine

Then apply it to a real object:

SwordShine
SwordShine

If you also want to learn pixel frame animation, you can follow the original author:

https://patreon.com/saint11

He’s the creator of Celeste.

If you’d like to read the content translated into Chinese, I recommend following 风农’s column:

https://space.bilibili.com/7647261/article

Read More

Here’s a blog I came across recently: https://mattwarren.org/. It’s all about .NET and the CLR, and there are a lot of great posts on it.

The content goes pretty deep and is a bit hardcore, so if you’ve got questions about how the CLR works under the hood, it’s worth a look.

Read More

In C#, how do you tell whether two anonymous types are the same type? And how is equality determined between instances of anonymous types?

Read More

What is the A* algorithm? How does it work? And where is it actually used?

Read More
TOP