Skip to content

Commit 830d006

Browse files
committed
Enable VSTHRD200 (Use "Async" suffix for async methods)
This rule remains disabled in test code to avoid requiring test methods to be renamed.
1 parent e6afaef commit 830d006

File tree

16 files changed

+53
-53
lines changed

16 files changed

+53
-53
lines changed

.editorconfig

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,6 @@ dotnet_sort_system_directives_first = true
77
# VSTHRD002: Avoid problematic synchronous waits
88
dotnet_diagnostic.VSTHRD002.severity = none
99

10-
# VSTHRD200: Use "Async" suffix for async methods
11-
dotnet_diagnostic.VSTHRD200.severity = none
12-
1310
[test/**/*.cs]
1411

1512
# MSML_GeneralName: This name should be PascalCased
@@ -30,6 +27,9 @@ dotnet_diagnostic.MSML_NoInstanceInitializers.severity = none
3027
# MSML_ParameterLocalVarName: Parameter or local variable name not standard
3128
dotnet_diagnostic.MSML_ParameterLocalVarName.severity = none
3229

30+
# VSTHRD200: Use "Async" suffix for async methods
31+
dotnet_diagnostic.VSTHRD200.severity = none
32+
3333
[test/Microsoft.ML.CodeAnalyzer.Tests/**.cs]
3434
# BaseTestClass does not apply for analyzer testing.
3535
# MSML_ExtendBaseTestClass: Test classes should be derived from BaseTestClass

src/Microsoft.Extensions.ML/ModelLoaders/UriModelLoader.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ internal void Start(Uri uri, TimeSpan period)
4646
{
4747
_timerPeriod = period;
4848
_uri = uri;
49-
if (LoadModel().ConfigureAwait(false).GetAwaiter().GetResult())
49+
if (LoadModelAsync().ConfigureAwait(false).GetAwaiter().GetResult())
5050
{
5151
StartReloadTimer();
5252
}
@@ -78,10 +78,10 @@ internal async Task RunAsync()
7878
cancellation.CancelAfter(TimeoutMilliseconds);
7979
Logger.UriReloadBegin(_logger, _uri);
8080

81-
var eTagMatches = await MatchEtag(_uri, _eTag);
81+
var eTagMatches = await MatchEtagAsync(_uri, _eTag);
8282
if (!eTagMatches)
8383
{
84-
await LoadModel();
84+
await LoadModelAsync();
8585
var previousToken = Interlocked.Exchange(ref _reloadToken, new ModelReloadToken());
8686
previousToken.OnReload();
8787
}
@@ -102,7 +102,7 @@ internal async Task RunAsync()
102102
}
103103
}
104104

105-
internal virtual async Task<bool> MatchEtag(Uri uri, string eTag)
105+
internal virtual async Task<bool> MatchEtagAsync(Uri uri, string eTag)
106106
{
107107
using (var client = new HttpClient())
108108
{
@@ -133,7 +133,7 @@ internal void StopReloadTimer()
133133
}
134134
}
135135

136-
internal virtual async Task<bool> LoadModel()
136+
internal virtual async Task<bool> LoadModelAsync()
137137
{
138138
//TODO: We probably need some sort of retry policy for this.
139139
try

src/Microsoft.ML.Core/Utilities/ResourceManagerUtils.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ public static string GetUrl(string suffix)
9898
/// <param name="timeout">An integer indicating the number of milliseconds to wait before timing out while downloading a resource.</param>
9999
/// <returns>The download results, containing the file path where the resources was (or should have been) downloaded to, and an error message
100100
/// (or null if there was no error).</returns>
101-
public async Task<ResourceDownloadResults> EnsureResource(IHostEnvironment env, IChannel ch, string relativeUrl, string fileName, string dir, int timeout)
101+
public async Task<ResourceDownloadResults> EnsureResourceAsync(IHostEnvironment env, IChannel ch, string relativeUrl, string fileName, string dir, int timeout)
102102
{
103103
var filePath = GetFilePath(ch, fileName, dir, out var error);
104104
if (File.Exists(filePath) || !string.IsNullOrEmpty(error))
@@ -110,11 +110,11 @@ public async Task<ResourceDownloadResults> EnsureResource(IHostEnvironment env,
110110
$"Could not create a valid URI from the base URI '{MlNetResourcesUrl}' and the relative URI '{relativeUrl}'");
111111
}
112112
return new ResourceDownloadResults(filePath,
113-
await DownloadFromUrl(env, ch, absoluteUrl.AbsoluteUri, fileName, timeout, filePath), absoluteUrl.AbsoluteUri);
113+
await DownloadFromUrlAsync(env, ch, absoluteUrl.AbsoluteUri, fileName, timeout, filePath), absoluteUrl.AbsoluteUri);
114114
}
115115

116116
/// <returns>Returns the error message if an error occurred, null if download was successful.</returns>
117-
private async Task<string> DownloadFromUrl(IHostEnvironment env, IChannel ch, string url, string fileName, int timeout, string filePath)
117+
private async Task<string> DownloadFromUrlAsync(IHostEnvironment env, IChannel ch, string url, string fileName, int timeout, string filePath)
118118
{
119119
using (var webClient = new WebClient())
120120
using (var downloadCancel = new CancellationTokenSource())

src/Microsoft.ML.Core/Utilities/ThreadUtils.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ namespace Microsoft.ML.Internal.Utilities
1212
{
1313
internal static partial class Utils
1414
{
15-
public static Task RunOnBackgroundThread(Action start) =>
16-
ImmediateBackgroundThreadPool.Queue(start);
15+
public static Task RunOnBackgroundThreadAsync(Action start) =>
16+
ImmediateBackgroundThreadPool.QueueAsync(start);
1717

18-
public static Task RunOnBackgroundThread(Action<object> start, object obj) =>
19-
ImmediateBackgroundThreadPool.Queue(start, obj);
18+
public static Task RunOnBackgroundThreadAsync(Action<object> start, object obj) =>
19+
ImmediateBackgroundThreadPool.QueueAsync(start, obj);
2020

2121
public static Thread RunOnForegroundThread(ParameterizedThreadStart start) =>
2222
new Thread(start) { IsBackground = false };
@@ -42,17 +42,17 @@ private static class ImmediateBackgroundThreadPool
4242
/// always end in the <see cref="TaskStatus.RanToCompletion"/> state; if the delegate throws
4343
/// an exception, it'll be allowed to propagate on the thread, crashing the process.
4444
/// </summary>
45-
public static Task Queue(Action threadStart) => Queue((Delegate)threadStart, null);
45+
public static Task QueueAsync(Action threadStart) => QueueAsync((Delegate)threadStart, null);
4646

4747
/// <summary>
4848
/// Queues an <see cref="Action{Object}"/> delegate and associated state to be executed immediately on another thread,
4949
/// and returns a <see cref="Task"/> that represents its eventual completion. The task will
5050
/// always end in the <see cref="TaskStatus.RanToCompletion"/> state; if the delegate throws
5151
/// an exception, it'll be allowed to propagate on the thread, crashing the process.
5252
/// </summary>
53-
public static Task Queue(Action<object> threadStart, object state) => Queue((Delegate)threadStart, state);
53+
public static Task QueueAsync(Action<object> threadStart, object state) => QueueAsync((Delegate)threadStart, state);
5454

55-
private static Task Queue(Delegate threadStart, object state)
55+
private static Task QueueAsync(Delegate threadStart, object state)
5656
{
5757
// Create the TaskCompletionSource used to represent this work.
5858
// Call sites only care about completion, not about the distinction between

src/Microsoft.ML.Data/Data/DataViewUtils.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ private static DataViewRowCursor ConsolidateCore(IChannelProvider provider, Data
367367
ch.Assert(localCursor.Position < 0);
368368
// Note that these all take ownership of their respective cursors,
369369
// so they all handle their disposal internal to the thread.
370-
workers[t] = Utils.RunOnBackgroundThread(() =>
370+
workers[t] = Utils.RunOnBackgroundThreadAsync(() =>
371371
{
372372
// This will be the last batch sent in the finally. If iteration procedes without
373373
// error, it will remain null, and be sent as a sentinel. If iteration results in
@@ -557,7 +557,7 @@ private DataViewRowCursor[] SplitCore(IChannelProvider ch, DataViewRowCursor inp
557557
// Set up and start the thread that consumes the input, and utilizes the InPipe
558558
// instances to compose the Batch objects. The thread takes ownership of the
559559
// cursor, and so handles its disposal.
560-
Task thread = Utils.RunOnBackgroundThread(
560+
Task thread = Utils.RunOnBackgroundThreadAsync(
561561
() =>
562562
{
563563
Batch lastBatch = null;

src/Microsoft.ML.Data/DataLoadSave/Binary/BinaryLoader.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1330,9 +1330,9 @@ public Cursor(BinaryLoader parent, IEnumerable<DataViewSchema.Column> columnsNee
13301330
_pipeGetters[c] = _pipes[c].GetGetter();
13311331
}
13321332
// The data structures are initialized. Now set up the workers.
1333-
_readerThread = Utils.RunOnBackgroundThread(ReaderWorker);
1333+
_readerThread = Utils.RunOnBackgroundThreadAsync(ReaderWorker);
13341334

1335-
_pipeTask = SetupDecompressTask();
1335+
_pipeTask = DecompressAsync();
13361336
}
13371337

13381338
protected override void Dispose(bool disposing)
@@ -1402,14 +1402,14 @@ protected override void Dispose(bool disposing)
14021402
base.Dispose(disposing);
14031403
}
14041404

1405-
private Task SetupDecompressTask()
1405+
private Task DecompressAsync()
14061406
{
14071407
Task[] pipeWorkers = new Task[_parent._threads];
14081408
long decompressSequence = -1;
14091409
long decompressSequenceLim = (long)_numBlocks * _actives.Length;
14101410
for (int w = 0; w < pipeWorkers.Length; ++w)
14111411
{
1412-
pipeWorkers[w] = Utils.RunOnBackgroundThread(() =>
1412+
pipeWorkers[w] = Utils.RunOnBackgroundThreadAsync(() =>
14131413
{
14141414
try
14151415
{

src/Microsoft.ML.Data/DataLoadSave/Binary/BinarySaver.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -664,15 +664,15 @@ public void SaveData(Stream stream, IDataView data, params int[] colIndices)
664664
Task[] compressionThreads = new Task[Environment.ProcessorCount];
665665
for (int i = 0; i < compressionThreads.Length; ++i)
666666
{
667-
compressionThreads[i] = Utils.RunOnBackgroundThread(
667+
compressionThreads[i] = Utils.RunOnBackgroundThreadAsync(
668668
() => CompressionWorker(toCompress, toWrite, activeColumns.Length, waiter, exMarshaller));
669669
}
670670
compressionTask = Task.WhenAll(compressionThreads);
671671
}
672672

673673
// While there is an advantage to putting the IO into a separate thread, there is not an
674674
// advantage to having more than one worker.
675-
Task writeThread = Utils.RunOnBackgroundThread(
675+
Task writeThread = Utils.RunOnBackgroundThreadAsync(
676676
() => WriteWorker(stream, toWrite, activeColumns, data.Schema, rowsPerBlock, _host, exMarshaller));
677677
sw.Start();
678678

src/Microsoft.ML.Data/DataLoadSave/Text/TextLoaderCursor.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ public LineReader(IMultiStreamSource files, int batchSize, int bufSize, bool has
427427
_cref = cref;
428428

429429
_queue = new BlockingQueue<LineBatch>(bufSize);
430-
_thdRead = Utils.RunOnBackgroundThread(ThreadProc);
430+
_thdRead = Utils.RunOnBackgroundThreadAsync(ThreadProc);
431431
}
432432

433433
public void Release()
@@ -691,7 +691,7 @@ public ParallelState(Cursor curs, out RowSet rows, int cthd)
691691

692692
for (int tid = 0; tid < _threads.Length; tid++)
693693
{
694-
_threads[tid] = Utils.RunOnBackgroundThread(ThreadProc, tid);
694+
_threads[tid] = Utils.RunOnBackgroundThreadAsync(ThreadProc, tid);
695695
}
696696
}
697697

src/Microsoft.ML.Data/DataView/CacheDataView.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ private void KickoffFiller(int[] columns)
360360
// They will not be caught by the big catch in the main thread, as filler is not running
361361
// in the main thread. Some sort of scheme by which these exceptions could be
362362
// cleanly handled would be more appropriate. See task 3740.
363-
var fillerThread = Utils.RunOnBackgroundThread(() => Filler(cursor, caches, waiter));
363+
var fillerThread = Utils.RunOnBackgroundThreadAsync(() => Filler(cursor, caches, waiter));
364364
_cacheFillerThreads.Add(fillerThread);
365365
}
366366

src/Microsoft.ML.Data/Transforms/RowShufflingTransformer.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,7 @@ public Cursor(IChannelProvider provider, int poolRows, DataViewRowCursor input,
546546
for (int i = 1; i < _bufferDepth; ++i)
547547
PostAssert(_toProduce, _blockSize);
548548

549-
_producerTask = LoopProducerWorker();
549+
_producerTask = ProduceAsync();
550550
}
551551

552552
protected override void Dispose(bool disposing)
@@ -586,7 +586,7 @@ public override ValueGetter<DataViewRowId> GetIdGetter()
586586
return _idGetter;
587587
}
588588

589-
private async Task LoopProducerWorker()
589+
private async Task ProduceAsync()
590590
{
591591
try
592592
{

src/Microsoft.ML.Sweeper/AsyncSweeper.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public interface IAsyncSweeper
4747
/// Propose a <see cref="ParameterSet"/>.
4848
/// </summary>
4949
/// <returns>A future <see cref="ParameterSet"/> and its id. Null if unavailable or cancelled.</returns>
50-
Task<ParameterSetWithId> Propose();
50+
Task<ParameterSetWithId> ProposeAsync();
5151

5252
/// <summary>
5353
/// Notify the sweeper of a finished run.
@@ -108,7 +108,7 @@ public void Update(int id, IRunResult result)
108108
}
109109
}
110110

111-
public Task<ParameterSetWithId> Propose()
111+
public Task<ParameterSetWithId> ProposeAsync()
112112
{
113113
if (_canceled)
114114
return Task.FromResult<ParameterSetWithId>(null);
@@ -272,7 +272,7 @@ private void UpdateBarrierStatus(int id)
272272
}
273273
}
274274

275-
public async Task<ParameterSetWithId> Propose()
275+
public async Task<ParameterSetWithId> ProposeAsync()
276276
{
277277
if (_cts.IsCancellationRequested)
278278
return null;

src/Microsoft.ML.TensorFlow/TensorflowUtils.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ internal static void DownloadIfNeeded(IHostEnvironment env, string url, string d
180180
{
181181
using (var ch = env.Start("Ensuring meta files are present."))
182182
{
183-
var ensureModel = ResourceManagerUtils.Instance.EnsureResource(env, ch, url, fileName, dir, timeout);
183+
var ensureModel = ResourceManagerUtils.Instance.EnsureResourceAsync(env, ch, url, fileName, dir, timeout);
184184
ensureModel.Wait();
185185
var errorResult = ResourceManagerUtils.GetErrorMessage(out var errorMessage, ensureModel.Result);
186186
if (errorResult != null)

src/Microsoft.ML.Transforms/Text/WordEmbeddingsExtractor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,7 @@ private string EnsureModelFile(IHostEnvironment env, out int linesToSkip, WordEm
628628
{
629629
string dir = kind == WordEmbeddingEstimator.PretrainedModelKind.SentimentSpecificWordEmbedding ? Path.Combine("Text", "Sswe") : "WordVectors";
630630
var url = $"{dir}/{modelFileName}";
631-
var ensureModel = ResourceManagerUtils.Instance.EnsureResource(Host, ch, url, modelFileName, dir, Timeout);
631+
var ensureModel = ResourceManagerUtils.Instance.EnsureResourceAsync(Host, ch, url, modelFileName, dir, Timeout);
632632
ensureModel.Wait();
633633
var errorResult = ResourceManagerUtils.GetErrorMessage(out var errorMessage, ensureModel.Result);
634634
if (errorResult != null)

test/Microsoft.Extensions.ML.Tests/UriLoaderTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,12 @@ public override ITransformer GetModel()
8686
return null;
8787
}
8888

89-
internal override Task<bool> LoadModel()
89+
internal override Task<bool> LoadModelAsync()
9090
{
9191
return Task.FromResult(true);
9292
}
9393

94-
internal override Task<bool> MatchEtag(Uri uri, string eTag)
94+
internal override Task<bool> MatchEtagAsync(Uri uri, string eTag)
9595
{
9696
return Task.FromResult(ETagMatches(uri, eTag));
9797
}

test/Microsoft.ML.Sweeper.Tests/TestSweeper.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ public void TestSimpleSweeperAsync()
145145
var paramSets = new List<ParameterSet>();
146146
for (int i = 0; i < sweeps; i++)
147147
{
148-
var task = sweeper.Propose();
148+
var task = sweeper.ProposeAsync();
149149
Assert.True(task.IsCompleted);
150150
paramSets.Add(task.Result.ParameterSet);
151151
var result = new RunResult(task.Result.ParameterSet, random.NextDouble(), true);
@@ -166,7 +166,7 @@ public void TestSimpleSweeperAsync()
166166
paramSets.Clear();
167167
for (int i = 0; i < sweeps; i++)
168168
{
169-
var task = gridSweeper.Propose();
169+
var task = gridSweeper.ProposeAsync();
170170
Assert.True(task.IsCompleted);
171171
paramSets.Add(task.Result.ParameterSet);
172172
}
@@ -202,7 +202,7 @@ public async Task TestDeterministicSweeperAsyncCancellation()
202202
int numCompleted = 0;
203203
for (int i = 0; i < sweeps; i++)
204204
{
205-
var task = sweeper.Propose();
205+
var task = sweeper.ProposeAsync();
206206
if (i < args.BatchSize - args.Relaxation)
207207
{
208208
Assert.True(task.IsCompleted);
@@ -252,7 +252,7 @@ public async Task TestDeterministicSweeperAsync()
252252
var paramSets = new List<ParameterSet>();
253253
for (int i = 0; i < sweeps; i++)
254254
{
255-
var task = sweeper.Propose();
255+
var task = sweeper.ProposeAsync();
256256
Assert.True(task.IsCompleted);
257257
paramSets.Add(task.CompletedResult().ParameterSet);
258258
var result = new RunResult(task.CompletedResult().ParameterSet, random.NextDouble(), true);
@@ -270,7 +270,7 @@ public async Task TestDeterministicSweeperAsync()
270270
var results = new List<KeyValuePair<int, IRunResult>>();
271271
for (int i = 0; i < args.BatchSize; i++)
272272
{
273-
var task = sweeper.Propose();
273+
var task = sweeper.ProposeAsync();
274274
Assert.True(task.IsCompleted);
275275
tasks[i] = task;
276276
if (task.CompletedResult() == null)
@@ -281,7 +281,7 @@ public async Task TestDeterministicSweeperAsync()
281281
// in the previous batch has been posted to the sweeper.
282282
for (int i = args.BatchSize; i < 2 * args.BatchSize; i++)
283283
{
284-
var task = sweeper.Propose();
284+
var task = sweeper.ProposeAsync();
285285
Assert.False(task.IsCompleted);
286286
tasks[i] = task;
287287
}
@@ -328,7 +328,7 @@ public void TestDeterministicSweeperAsyncParallel()
328328
sleeps[i] = random.Next(10, 100);
329329
var r = Task.Run(() => Parallel.For(0, sweeps, options, (int i) =>
330330
{
331-
var task = sweeper.Propose();
331+
var task = sweeper.ProposeAsync();
332332
task.Wait();
333333
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
334334
var paramWithId = task.Result;
@@ -386,7 +386,7 @@ public async Task TestNelderMeadSweeperAsync()
386386

387387
for (int i = 0; i < sweeps; i++)
388388
{
389-
var paramWithId = await sweeper.Propose();
389+
var paramWithId = await sweeper.ProposeAsync();
390390
if (paramWithId == null)
391391
return;
392392
var result = new RunResult(paramWithId.ParameterSet, metrics[i], true);

0 commit comments

Comments
 (0)