.NET ヘルプ

C# スパン(開発者のための仕組み)

更新済み 3月 6, 2024
共有:

スパン C# 7.2で導入されたSpanの一部としての型 System名前空間内のstruct。 これは任意のメモリの連続した領域を表すように設計されています。 配列や管理ヒープのようなコレクションとは異なり、Span は指し示すスタックメモリやメモリ領域の所有権を持っていません。 代わりに、既存のメモリブロックに対して軽量なビューを提供します。 この特性は、追加のオーバーヘッドや安全でないコードのシナリオを発生させることなく、メモリバッファーを効率的に扱う必要があるシナリオにおいて、Span を特に強力にします。 この記事の後半では、導入についても説明します IronPDF 以下の内容を日本語に翻訳してください:

のライブラリ アイアンソフトウェア.

スパンの主要特性

メモリ管理

C#のSpanは、従来のヒープ割り当てに頼ることなくメモリを直接操作することを開発者に許可します。 それは既存の配列や他のメモリソースからメモリのスライスを作成する方法を提供し、追加のメモリコピーを必要としません。

ゼロコピー抽象化

C# Spanの際立った特徴の一つは、ゼロコピー抽象化です。 データを重複させるのではなく、Spanは既存のメモリを効率的に参照する方法を提供します。 これは、大量のデータをコピーすることが不可能またはコストがかかりすぎるシナリオにおいて特に有益です。

ポインタのような操作

C#は伝統的に高水準で安全な言語でしたが、SpanはCやC++のような言語でポインターを操作するのと同様に、低レベルのメモリ操作の要素を導入します。 開発者は、C#の安全で管理された特徴を犠牲にすることなく、ポインタのような操作を実行することができます。

4. 不変の性質

その低レベルのメモリアクセスに対する能力にもかかわらず、C# Spanは不変です。 これは、メモリの操作を許可する一方で、意図しない変更を防ぐことによって安全性を確保することを意味します。

using System;
class Program
{
    void Main()
    {
        int [] array = { 1, 2, 3, 4, 5 };
        // Create a span that points to the entire array
        Span<int> span = array;
        // Modify the data using the span
        span [2] = 10;
        // Print the modified array
        foreach (var item in array)
        {
            Console.WriteLine(item);
        }
    }
}
using System;
class Program
{
    void Main()
    {
        int [] array = { 1, 2, 3, 4, 5 };
        // Create a span that points to the entire array
        Span<int> span = array;
        // Modify the data using the span
        span [2] = 10;
        // Print the modified array
        foreach (var item in array)
        {
            Console.WriteLine(item);
        }
    }
}
Imports System
Friend Class Program
	Private Sub Main()
		Dim array() As Integer = { 1, 2, 3, 4, 5 }
		' Create a span that points to the entire array
		Dim span As Span(Of Integer) = array
		' Modify the data using the span
		span (2) = 10
		' Print the modified array
		For Each item In array
			Console.WriteLine(item)
		Next item
	End Sub
End Class
VB   C#

"ReadOnlySpan"

スペイン語の間 ReadOnlySpanは変更可能であり、基礎となるデータへの変更を許可する 不変のメモリビューです。 それは隣接するメモリ領域への読み取り専用インターフェースを提供し、データを変更せずに読み取るだけでよい場合に適しています。

以下は重要なポイントです。

1. 読み取り専用ビュー

名前が示すように、ReadOnlySpan メモリブロックの読み取り専用ビューを作成することができます。 これは、ReadOnlySpanを介して要素を変更できないことを意味します。.

メモリ表現

スパンのように"ReadOnlySpan" それが指し示すメモリを所有していません。 配列やスタックに割り当てられたメモリ、あるいはネイティブメモリを指す既存のメモリを指します。

パフォーマンスの利点

スパンのように"ReadOnlySpan" 大量のデータを扱う場合、コピーの必要性を減らすため、従来のコレクション型と比較してより優れたパフォーマンスを提供できます。

範囲チェックなし

スパン"ReadOnlySpan" 境界チェックを行わない。 操作が基盤となるメモリの範囲内に収まるようにすることは、開発者の責任です。

5. 配列スライシングでの使用

"ReadOnlySpan" スライシングをサポートしており、元のメモリの一部を参照するサブスパンを作成することができます。

using System;
class Program
{
    static void Main()
    {
        int [] array = { 1, 2, 3, 4, 5 };
        // Create a read-only span that points to the entire array
        ReadOnlySpan<int> readOnlySpan = array;
        // Access and print the data through the read-only span
        foreach (var item in readOnlySpan)
        {
            Console.WriteLine(item);
        }
        // Note: The following line would result in a compilation error since readOnlySpan is read-only.
        // readOnlySpan [2] = 10;
    }
}
using System;
class Program
{
    static void Main()
    {
        int [] array = { 1, 2, 3, 4, 5 };
        // Create a read-only span that points to the entire array
        ReadOnlySpan<int> readOnlySpan = array;
        // Access and print the data through the read-only span
        foreach (var item in readOnlySpan)
        {
            Console.WriteLine(item);
        }
        // Note: The following line would result in a compilation error since readOnlySpan is read-only.
        // readOnlySpan [2] = 10;
    }
}
Imports System
Friend Class Program
	Shared Sub Main()
		Dim array() As Integer = { 1, 2, 3, 4, 5 }
		' Create a read-only span that points to the entire array
		Dim readOnlySpan As ReadOnlySpan(Of Integer) = array
		' Access and print the data through the read-only span
		For Each item In readOnlySpan
			Console.WriteLine(item)
		Next item
		' Note: The following line would result in a compilation error since readOnlySpan is read-only.
		' readOnlySpan [2] = 10;
	End Sub
End Class
VB   C#

ReadOnlySpan を作成して使用する方法は多くあります。 以下はいくつかの例です。

1. 文字列からReadOnlySpanを作成する

string msg = "Hello, World!";
ReadOnlySpan<char> span1 = msg.AsSpan();
// Read-only manipulation
char firstChar = span1 [0];
Console.WriteLine(firstChar); // Outputs: H
string msg = "Hello, World!";
ReadOnlySpan<char> span1 = msg.AsSpan();
// Read-only manipulation
char firstChar = span1 [0];
Console.WriteLine(firstChar); // Outputs: H
Dim msg As String = "Hello, World!"
Dim span1 As ReadOnlySpan(Of Char) = msg.AsSpan()
' Read-only manipulation
Dim firstChar As Char = span1 (0)
Console.WriteLine(firstChar) ' Outputs: H
VB   C#

サブストリングの操作

'Use Slice on the ReadOnlySpan'を使用する

ReadOnlySpan<char> substringSpan = spanFromString.Slice(startIndex, length);
ReadOnlySpan<char> substringSpan = spanFromString.Slice(startIndex, length);
Dim substringSpan As ReadOnlySpan(Of Char) = spanFromString.Slice(startIndex, length)
VB   C#

メソッドに部分文字列を渡す

ReadOnlySpanを渡す メソッドのパラメーターとして。

void ProcessSubstringfromReadOnlySpan(ReadOnlySpan<char> substring)
{
    // Perform operations on the substring
}
// Usage
ProcessSubstringfromReadOnlySpan(spanFromString.Slice(startIndex, length));
void ProcessSubstringfromReadOnlySpan(ReadOnlySpan<char> substring)
{
    // Perform operations on the substring
}
// Usage
ProcessSubstringfromReadOnlySpan(spanFromString.Slice(startIndex, length));
Private Sub ProcessSubstringfromReadOnlySpan(ByVal substring As ReadOnlySpan(Of Char))
	' Perform operations on the substring
End Sub
' Usage
ProcessSubstringfromReadOnlySpan(spanFromString.Slice(startIndex, length))
VB   C#

文字列内の検索

"ReadOnlySpan" 文字列内を IndexOf で検索するため().

int index = stringSpan.IndexOf('W');
int index = stringSpan.IndexOf('W');
Dim index As Integer = stringSpan.IndexOf("W"c)
VB   C#

メモリマップトファイルの使用

"ReadOnlySpan" メモリマップトファイルを使用すると、より効率的に行うことができます。

using (var memmf = MemoryMappedFile.CreateFromFile("data.bin"))
{
    using (var accessor = memmf.CreateViewAccessor())
    {
        ReadOnlySpan<byte> dataSpan;
        accessor.Read(0, out dataSpan);
        // Process data directly from the memory-mapped file
        ProcessData(dataSpan);
    }
}
using (var memmf = MemoryMappedFile.CreateFromFile("data.bin"))
{
    using (var accessor = memmf.CreateViewAccessor())
    {
        ReadOnlySpan<byte> dataSpan;
        accessor.Read(0, out dataSpan);
        // Process data directly from the memory-mapped file
        ProcessData(dataSpan);
    }
}
Using memmf = MemoryMappedFile.CreateFromFile("data.bin")
	Using accessor = memmf.CreateViewAccessor()
		Dim dataSpan As ReadOnlySpan(Of Byte) = Nothing
		accessor.Read(0, dataSpan)
		' Process data directly from the memory-mapped file
		ProcessData(dataSpan)
	End Using
End Using
VB   C#

6. 効率的な文字列操作

"ReadOnlySpan" 効率的な文字列操作に使用できます。

// Replace a character in a substring without creating a new string
spanFromString.Slice(startIndex, length).CopyTo(newSpan);
// Replace a character in a substring without creating a new string
spanFromString.Slice(startIndex, length).CopyTo(newSpan);
' Replace a character in a substring without creating a new string
spanFromString.Slice(startIndex, length).CopyTo(newSpan)
VB   C#

7. APIに部分文字列を渡す

文字範囲を操作する外部ライブラリやAPIを使用する際。

void ExternalApiMethod(ReadOnlySpan<char> data)
{
    // Call the external API with the character span
}
// Usage
ExternalApiMethod(spanFromString.Slice(startIndex, length));
void ExternalApiMethod(ReadOnlySpan<char> data)
{
    // Call the external API with the character span
}
// Usage
ExternalApiMethod(spanFromString.Slice(startIndex, length));
Private Sub ExternalApiMethod(ByVal data As ReadOnlySpan(Of Char))
	' Call the external API with the character span
End Sub
' Usage
ExternalApiMethod(spanFromString.Slice(startIndex, length))
VB   C#

"ReadOnlySpan" メモリ割り当てやコピーを最小限に抑える必要があるシナリオにおいて、文字列をより効率的に扱う方法を提供します。 これは、パフォーマンスが重要なコードを最適化するための強力なツールであり、大量の文字列データを扱う際に特に有益です。

スパンの制限

C#のSpanは多くの利点を持つ強力な機能ですが、特に連続メモリと非連続メモリの文脈において、いくつかの制限や考慮事項が伴います。 これらの制限を見てみましょう。

連続メモリバッファ

自動メモリ管理なし

スパン 指しているメモリを管理しません。 基礎となる管理メモリが解放されたりスコープを外れたりすると、Spanを使用することは 未定義の動作または潜在的なクラッシュを引き起こします。 開発者は、Spanを使用する際に、基礎となるメモリが依然として有効であることを確認する必要があります。.

1.2 ガベージコレクションなし

スパン メモリを所有していないため、それはガベージコレクションの対象にはなりません。 したがって、スタックに割り当てられたメモリや、Spanよりも短いライフタイムを持つメモリを扱う際には注意が必要です。 それ自体。

境界チェックは無効です

スパン 読み取り専用の範囲 デフォルトでは境界チェックを実行しません。 これは慎重に使用しないと無効なメモリ位置にアクセスする可能性があります。 開発者はSpan上の操作を手動で確実に行う必要があります。 基礎メモリの範囲内に留まる。

非連続メモリのサポートなし

スパン 連続メモリと連携するように設計されています。 不連続メモリを持っている場合や、より複雑なデータ構造を表現する必要がある場合は、Span 最適な選択肢ではない可能性があります。

すべての操作がサポートされるわけではありません

スペイン語の間 多くの一般的な操作(スライス、インデックス、イテレーションなど)をサポートしていますが、すべての操作がサポートされているわけではありません。 例えば、Spanをリサイズすることはできません。基盤となるメモリの長さを変更する操作は許可されていません。

1.6 限定プラットフォーム互換性

スペイン語の間 .NET Standard および .NET Core の一部であるため、すべてのプラットフォームや環境で利用できるわけではありません。 ターゲット プラットフォームが Span をサポートしていることを確認することは重要です。 コードで使用する予定がある場合。

2. 非連続メモリバッファ

2.1 非連続メモリの限定サポート

"ReadOnlySpan" は、主に連続したメモリブロックまたはバッファとシームレスに動作するように設計されています。 非連続のメモリバッファやメモリにギャップのある構造が関与するシナリオでは、最適な選択肢ではないかもしれません。

構造的制限 2.2

ReadOnlySpanに適合しない非連続メモリに依存する特定のデータ構造やシナリオがあります。. 例えば、連結リストやグラフ構造のようなデータ構造は、ReadOnlySpanの連続メモリ要件のために適していないかもしれません。.

2.3 複雑なポインタ操作

非連続メモリに関連する状況、特に複雑なポインタ算術が必要な場合、ReadOnlySpan C++のような言語の生のポインタと同じ低レベルの制御と柔軟性を提供しない場合があります。 そのような場合、ポインターを使用するアンセーフコードを利用する方が適切である可能性があります。

2.4 一部のAPIにおける直接サポートの欠如

連続メモリと同様に、すべてのAPIやライブラリがReadOnlySpanで表される非連続メモリを直接サポートするとは限らないことに注意することが重要です。. このようなシナリオに適応するには、互換性を確保するために追加の中間ステップや変換が必要になるかもしれません。

Span および Unmanaged Memory

C#では、Spanを使用すると、管理されていないメモリに対して制御された効率的な方法でメモリ関連の操作を実行できます。 アンマネージメモリとは、.NETランタイムのガベージコレクタによって管理されていないメモリのことを指し、ネイティブメモリの割り当てや解放を伴うことが多いです。 ここでは、C#でアンマネージメモリを使用するためにSpanを活用する方法を説明します。

非管理メモリの割り当て

アンマネージドメモリを割り当てるには、System.Runtime.InteropServices.MemoryMarshal クラスを使用できます。 Marshal.AllocHGlobal メソッドはメモリを割り当て、割り当てられたブロックへのポインタを返します。 割り当てられたメモリまたはメモリアドレスは、unmanagedMemory ポインタに保持され、読み書きアクセスが可能です。 連続したメモリ領域は簡単にアクセスできます。

using System;
using System.Runtime.InteropServices;
class Program
{
    static void Main()
    {
        const int bufferSize = 100;
        IntPtr unmanagedMemory = Marshal.AllocHGlobal(bufferSize);
        // Create a Span from the unmanaged memory
        Span<byte> span = new Span<byte>(unmanagedMemory.ToPointer(), bufferSize);
        // Use the Span as needed...
        // Don't forget to free the unmanaged memory when done
        Marshal.FreeHGlobal(unmanagedMemory);
    }
}
using System;
using System.Runtime.InteropServices;
class Program
{
    static void Main()
    {
        const int bufferSize = 100;
        IntPtr unmanagedMemory = Marshal.AllocHGlobal(bufferSize);
        // Create a Span from the unmanaged memory
        Span<byte> span = new Span<byte>(unmanagedMemory.ToPointer(), bufferSize);
        // Use the Span as needed...
        // Don't forget to free the unmanaged memory when done
        Marshal.FreeHGlobal(unmanagedMemory);
    }
}
Imports System
Imports System.Runtime.InteropServices
Friend Class Program
	Shared Sub Main()
		Const bufferSize As Integer = 100
		Dim unmanagedMemory As IntPtr = Marshal.AllocHGlobal(bufferSize)
		' Create a Span from the unmanaged memory
		Dim span As New Span(Of Byte)(unmanagedMemory.ToPointer(), bufferSize)
		' Use the Span as needed...
		' Don't forget to free the unmanaged memory when done
		Marshal.FreeHGlobal(unmanagedMemory)
	End Sub
End Class
VB   C#

上記のソースコードでは、Marshal.AllocHGlobalを使用して非管理メモリのブロックを割り当て、その後、Spanを作成します。 アンマネージドメモリから取得したポインタを使用する。 これにより、慣れ親しんだSpan APIを使用して、非管理メモリを操作できるようになります。 アンマネージドメモリを使用するときは、メモリの割り当てと割り当て解除の管理が自分の責任であることに注意することが重要です。

アンマネージドメモリへのデータのコピーおよびアンマネージドメモリからのデータのコピー

スパンは Slice、CopyTo、ToArray などのメソッドを提供し、管理メモリと非管理メモリ間でデータを効率的にコピーするために使用できます。

using System;
using System.Runtime.InteropServices;
class Program
{
    static void Main()
    {
        // Managed array to copy data from
        int [] sourceArray = { 1, 2, 3, 4, 5 };
        // Allocate unmanaged memory for the destination data
        IntPtr destinationPointer = MemoryMarshal.Allocate<int>(sourceArray.Length);
        try
        {
            // Create a Span<int> from the source array
            Span<int> sourceSpan = sourceArray;
            // Create a Span<int> from the allocated unmanaged memory
            Span<int> destinationSpan = MemoryMarshal.Cast<int, byte>(destinationPointer, sourceArray.Length);
            // Copy data from the source Span<int> to the destination Span<int>
            sourceSpan.CopyTo(destinationSpan);
            // Print the values in the destination memory
            Console.WriteLine("Values in the destination memory:");
            foreach (var value in destinationSpan)
            {
                Console.Write($"{value} ");
            }
        }
        finally
        {
            // Deallocate the unmanaged memory when done
            MemoryMarshal.Free(destinationPointer);
        }
    }
}
using System;
using System.Runtime.InteropServices;
class Program
{
    static void Main()
    {
        // Managed array to copy data from
        int [] sourceArray = { 1, 2, 3, 4, 5 };
        // Allocate unmanaged memory for the destination data
        IntPtr destinationPointer = MemoryMarshal.Allocate<int>(sourceArray.Length);
        try
        {
            // Create a Span<int> from the source array
            Span<int> sourceSpan = sourceArray;
            // Create a Span<int> from the allocated unmanaged memory
            Span<int> destinationSpan = MemoryMarshal.Cast<int, byte>(destinationPointer, sourceArray.Length);
            // Copy data from the source Span<int> to the destination Span<int>
            sourceSpan.CopyTo(destinationSpan);
            // Print the values in the destination memory
            Console.WriteLine("Values in the destination memory:");
            foreach (var value in destinationSpan)
            {
                Console.Write($"{value} ");
            }
        }
        finally
        {
            // Deallocate the unmanaged memory when done
            MemoryMarshal.Free(destinationPointer);
        }
    }
}
Imports System
Imports System.Runtime.InteropServices
Friend Class Program
	Shared Sub Main()
		' Managed array to copy data from
		Dim sourceArray() As Integer = { 1, 2, 3, 4, 5 }
		' Allocate unmanaged memory for the destination data
		Dim destinationPointer As IntPtr = MemoryMarshal.Allocate(Of Integer)(sourceArray.Length)
		Try
			' Create a Span<int> from the source array
			Dim sourceSpan As Span(Of Integer) = sourceArray
			' Create a Span<int> from the allocated unmanaged memory
			Dim destinationSpan As Span(Of Integer) = MemoryMarshal.Cast(Of Integer, Byte)(destinationPointer, sourceArray.Length)
			' Copy data from the source Span<int> to the destination Span<int>
			sourceSpan.CopyTo(destinationSpan)
			' Print the values in the destination memory
			Console.WriteLine("Values in the destination memory:")
			For Each value In destinationSpan
				Console.Write($"{value} ")
			Next value
		Finally
			' Deallocate the unmanaged memory when done
			MemoryMarshal.Free(destinationPointer)
		End Try
	End Sub
End Class
VB   C#

この例では:

MemoryMarshal.Allocate(メモリマシャル・アロケート)(sourceArray.Length

ソース配列.Length) 宛先データのために管理されていないメモリを割り当てます。 MemoryMarshal.Cast<int, byte>(destinationPointer、sourceArray.Length) スパンを作成します 割り当てられたアンマネージドメモリから。 sourceSpan.CopyTo(宛先スパン) このメソッドは、管理対象の配列から非管理メモリにデータをコピーします。 コピー操作を検証するために、宛先メモリの値が印刷されます。 The MemoryMarshal.Free(デスティネーションポインター) このメソッドは、使用が完了したときに非管理メモリを解放するために使用されます。

アンセーフコードの使用

管理されていないメモリを扱う際には、ポインタを使用したunsafeコードも使用することができます。 そのような場合、Unsafe.AsPointerを使用して Span からポインタを取得することができます。() メソッド。

using System;
using System.Runtime.InteropServices;
class Program
{
    static void Main()
    {
        const int bufferSize = 100;
        IntPtr unmanagedMemory = Marshal.AllocHGlobal(bufferSize);
        // Create a Span from the unmanaged memory
        Span<byte> span = new Span<byte>(unmanagedMemory.ToPointer(), bufferSize);
        // Use unsafe code to work with pointers
        // ref t
        unsafe
        {
            byte* pointer = (byte*)Unsafe.AsPointer(ref struct MemoryMarshal.GetReference(span));
            // Use the pointer as needed...
        }
        // Don't forget to free the unmanaged memory when done
        Marshal.FreeHGlobal(unmanagedMemory);
    }
}
using System;
using System.Runtime.InteropServices;
class Program
{
    static void Main()
    {
        const int bufferSize = 100;
        IntPtr unmanagedMemory = Marshal.AllocHGlobal(bufferSize);
        // Create a Span from the unmanaged memory
        Span<byte> span = new Span<byte>(unmanagedMemory.ToPointer(), bufferSize);
        // Use unsafe code to work with pointers
        // ref t
        unsafe
        {
            byte* pointer = (byte*)Unsafe.AsPointer(ref struct MemoryMarshal.GetReference(span));
            // Use the pointer as needed...
        }
        // Don't forget to free the unmanaged memory when done
        Marshal.FreeHGlobal(unmanagedMemory);
    }
}
Imports System
Imports System.Runtime.InteropServices
Friend Class Program
	Shared Sub Main()
		Const bufferSize As Integer = 100
		Dim unmanagedMemory As IntPtr = Marshal.AllocHGlobal(bufferSize)
		' Create a Span from the unmanaged memory
		Dim span As New Span(Of Byte)(unmanagedMemory.ToPointer(), bufferSize)
		' Use unsafe code to work with pointers
		' ref t
'INSTANT VB TODO TASK: C# 'unsafe' code is not converted by Instant VB:
'		unsafe
'		{
'			byte* pointer = (byte*)Unsafe.AsPointer(ref struct MemoryMarshal.GetReference(span));
'			' Use the pointer as needed...
'		}
		' Don't forget to free the unmanaged memory when done
		Marshal.FreeHGlobal(unmanagedMemory)
	End Sub
End Class
VB   C#

この例では、Unsafe.AsPointerメソッドを使用してSpanからポインタを取得します。 これは、ポインタを直接操作する際にアンセーフコードを使用できるようにします。

忘れないでください。アンマネージドメモリを使用する際は、メモリリークを避けるために、メモリの割り当てと解放を適切に管理することが重要です。 適切な方法(例:Marshal.FreeHGlobal)を使用して、必ずアンマネージメモリを解放してください。(). さらに、アンセーフコードを使用する際には注意を払いましょう。適切に処理されない場合、潜在的なセキュリティリスクを引き起こす可能性があります。

スパンおよび非同期メソッド呼び出し

C#で非同期メソッド呼び出しと共にSpanを使用することは、特に大量のデータやI/O操作を扱う際に強力な組み合わせです。 目標は、データの不必要なコピーを避けつつ、非同期操作を効率的に処理することです。 非同期シナリオでどのようにSpanを活用できるかを探求しましょう:

1. 非同期I/O操作:

ストリームへのデータの読み取りや書き込みなどの非同期I/O操作を扱う場合、Memoryを使用することができます または Span 追加のバッファを作成せずに効率的にデータを処理するために。

async Task ProcessDataAsync(Stream stream)
{
    const int bufferSize = 4096;
    byte [] buffer = new byte [bufferSize];
    while (true)
    {
        int bytesRead = await stream.ReadAsync(buffer.AsMemory());
        if (bytesRead == 0)
            break;
        // Process the data using Span without unnecessary copying
        ProcessData(buffer.AsSpan(0, bytesRead));
    }
}
void ProcessData(Span<byte> data)
{
    // Perform operations on the data
}
async Task ProcessDataAsync(Stream stream)
{
    const int bufferSize = 4096;
    byte [] buffer = new byte [bufferSize];
    while (true)
    {
        int bytesRead = await stream.ReadAsync(buffer.AsMemory());
        if (bytesRead == 0)
            break;
        // Process the data using Span without unnecessary copying
        ProcessData(buffer.AsSpan(0, bytesRead));
    }
}
void ProcessData(Span<byte> data)
{
    // Perform operations on the data
}
Async Function ProcessDataAsync(ByVal stream As Stream) As Task
	Const bufferSize As Integer = 4096
	Dim buffer(bufferSize - 1) As Byte
	Do
		Dim bytesRead As Integer = Await stream.ReadAsync(buffer.AsMemory())
		If bytesRead = 0 Then
			Exit Do
		End If
		' Process the data using Span without unnecessary copying
		ProcessData(buffer.AsSpan(0, bytesRead))
	Loop
End Function
Private Sub ProcessData(ByVal data As Span(Of Byte))
	' Perform operations on the data
End Sub
VB   C#

この例では、ReadAsync メソッドは非同期的にストリームからデータをバッファに読み込みます。 ProcessDataメソッドは、その後、Spanから直接データを処理します。 別のバッファにコピーせずに。

2. 非同期ファイル操作:

I/O処理と同様に、非同期ファイル操作を扱う際には、追加のコピーを行わずにデータを効率的に処理するためにSpanを使用できます。

async Task ProcessFileAsync(string filePath)
{
    const int bufferSize = 4096;
    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    {
        byte [] buffer = new byte [bufferSize];
        while (true)
        {
            int bytesRead = await fileStream.ReadAsync(buffer.AsMemory());
            if (bytesRead == 0)
                break;
            // Process the data using Span without unnecessary copying
            ProcessData(buffer.AsSpan(0, bytesRead));
        }
    }
}
void ProcessData(Span<byte> data)
{
    // Perform operations on the data
}
async Task ProcessFileAsync(string filePath)
{
    const int bufferSize = 4096;
    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    {
        byte [] buffer = new byte [bufferSize];
        while (true)
        {
            int bytesRead = await fileStream.ReadAsync(buffer.AsMemory());
            if (bytesRead == 0)
                break;
            // Process the data using Span without unnecessary copying
            ProcessData(buffer.AsSpan(0, bytesRead));
        }
    }
}
void ProcessData(Span<byte> data)
{
    // Perform operations on the data
}
Async Function ProcessFileAsync(ByVal filePath As String) As Task
	Const bufferSize As Integer = 4096
	Using fileStream As New FileStream(filePath, FileMode.Open, FileAccess.Read)
		Dim buffer(bufferSize - 1) As Byte
		Do
			Dim bytesRead As Integer = Await fileStream.ReadAsync(buffer.AsMemory())
			If bytesRead = 0 Then
				Exit Do
			End If
			' Process the data using Span without unnecessary copying
			ProcessData(buffer.AsSpan(0, bytesRead))
		Loop
	End Using
End Function
Private Sub ProcessData(ByVal data As Span(Of Byte))
	' Perform operations on the data
End Sub
VB   C#

ここで、ReadAsyncメソッドはファイルストリームからバッファにデータを読み込み、ProcessDataメソッドはSpanから直接データを処理します。.

3. 非同期タスク処理:

データを生成または消費する非同期タスクを扱う際には、Memoryを使用することができます。 または Span 不必要なコピーを避けるため。

async Task<int> ProcessDataAsync(int [] data)
{
    // Asynchronous processing of data
    await Task.Delay(1000);
    // Returning the length of the processed data
    return data.Length;
}
async Task Main()
{
    int [] inputData = Enumerable.Range(1, 1000).ToArray();
    // Process the data asynchronously without copying
    int processedLength = await ProcessDataAsync(inputData.AsMemory());
    Console.WriteLine($"Processed data length: {processedLength}");
}
async Task<int> ProcessDataAsync(int [] data)
{
    // Asynchronous processing of data
    await Task.Delay(1000);
    // Returning the length of the processed data
    return data.Length;
}
async Task Main()
{
    int [] inputData = Enumerable.Range(1, 1000).ToArray();
    // Process the data asynchronously without copying
    int processedLength = await ProcessDataAsync(inputData.AsMemory());
    Console.WriteLine($"Processed data length: {processedLength}");
}
Async Function ProcessDataAsync(ByVal data() As Integer) As Task(Of Integer)
	' Asynchronous processing of data
	Await Task.Delay(1000)
	' Returning the length of the processed data
	Return data.Length
End Function
Async Function Main() As Task
	Dim inputData() As Integer = Enumerable.Range(1, 1000).ToArray()
	' Process the data asynchronously without copying
	Dim processedLength As Integer = Await ProcessDataAsync(inputData.AsMemory())
	Console.WriteLine($"Processed data length: {processedLength}")
End Function
VB   C#

この例では、ProcessDataAsync メソッドがデータを非同期に処理し、追加のコピーを必要とせずに処理されたデータの長さを返します。

IronPDFの紹介

IronPDF これは、から提供される最新のC# PDFライブラリです。 アイアンソフトウェア C# コードを使用して動的に美しいPDFドキュメントを即座に生成することができます。 IronPDFは、HTMLからのPDF生成、HTMLコンテンツのPDFへの変換、PDFファイルの結合や分割など、さまざまな機能を提供します。

IronPDFの主な機能はその HTMLからPDFへ レイアウトとスタイルを保つ関数。 WebコンテンツからPDFを生成することができるので、レポート、請求書、ドキュメントに最適です。 このツールは、HTMLファイル、URL、およびHTML文字列をPDFファイルに変換することをサポートしています。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

インストール

IronPDFは以下を使用してインストールできます NuGet パッケージ マネージャー コンソールまたはVisual Studioパッケージ マネージャーを使用します。

dotnet add package IronPdf
// Or
Install-Package IronPdf
dotnet add package IronPdf
// Or
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf Install-Package IronPdf
VB   C#

C# スパン (開発者向けの動作): 図1 - NuGetパッケージマネージャの検索バーに「ironpdf」と入力してIronPDFをインストールします。

using System;
class Program
{
    static void Main()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        var displayFirstName = "<p>First Name is Joe</p>".AsSpan();
        var displayLastName = "<p>First Name is Doe</p>".AsSpan();
        var displayAddress = "<p>12th Main, 7Th Cross, New York</p>".AsSpan();
        var start = @"<!DOCTYPE html>
<html>
<body>".AsSpan();
        var end = @"<!DOCTYPE html>
<html>
<body>";
        var content = string.Concat(start, displayFirstName, displayLastName, string.Concat(displayAddress, end));
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("span.pdf");
    }
}
using System;
class Program
{
    static void Main()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        var displayFirstName = "<p>First Name is Joe</p>".AsSpan();
        var displayLastName = "<p>First Name is Doe</p>".AsSpan();
        var displayAddress = "<p>12th Main, 7Th Cross, New York</p>".AsSpan();
        var start = @"<!DOCTYPE html>
<html>
<body>".AsSpan();
        var end = @"<!DOCTYPE html>
<html>
<body>";
        var content = string.Concat(start, displayFirstName, displayLastName, string.Concat(displayAddress, end));
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("span.pdf");
    }
}
Imports System
Friend Class Program
	Shared Sub Main()
		Console.WriteLine("Generating PDF using IronPDF.")
		Dim displayFirstName = "<p>First Name is Joe</p>".AsSpan()
		Dim displayLastName = "<p>First Name is Doe</p>".AsSpan()
		Dim displayAddress = "<p>12th Main, 7Th Cross, New York</p>".AsSpan()
		Dim start = "<!DOCTYPE html>
<html>
<body>".AsSpan()
		Dim [end] = "<!DOCTYPE html>
<html>
<body>"
		Dim content = String.Concat(start, displayFirstName, displayLastName, String.Concat(displayAddress, [end]))
		Dim pdfDocument = New ChromePdfRenderer()
		pdfDocument.RenderHtmlAsPdf(content).SaveAs("span.pdf")
	End Sub
End Class
VB   C#

この例では、SpanIronPDFを使用してPDFドキュメントを生成しています。

出力:

C# スパン(開発者にとっての動作原理):図2 - コンソール出力

生成されたPDF:

C# スパン (開発者向けの仕組み): 図3 - PDF出力

ライセンス(無料トライアル利用可能)

IronPDF. このキーはappsettings.jsonに配置する必要があります。

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

試用ライセンスを取得するためにメールアドレスを提供してください。

結論

スパン C#において、メモリを操作するための強力かつ効率的な方法を提供し、パフォーマンスと柔軟性の面で大きなメリットがあります。 その非所有の連続した性質は、メモリ割り当てとコピーを最小限に抑えることが重要なシナリオに特に適しています。 Spanを活用することで、開発者は文字列操作から高性能な数値処理に至るまで、さまざまなアプリケーションにおいて優れたパフォーマンスを実現できます。 特徴を理解し、その制限を考慮することで、開発者はSpanを活用できます。 さまざまなメモリ操作タスクを安全かつ効率的に実行するために。 以下の内容を日本語に翻訳してください:

Along with

その他 IronPDF、待機やyieldの制限なしに素晴らしいPDFドキュメントを生成するために使用できます。

続いて 無料試用 長期使用のために。 IronPDFの使い方について詳しく知りたい方は、こちらをご覧ください ドキュメント ページ

< 以前
C# IDE(開発者向けの仕組み)
次へ >
Opentelemetry C#(開発者向けの仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >