我对理解异步方法的执行存在问题,该方法作为参数传递给StartNew
的{{1}}方法。你能解释一下它究竟会起作用吗?
我有TaskFactory
类,其中包含用户标识符。
UserInfo
我有public sealed class UserInfo
{
[ThreadStatic]
public static Guid UserId;
}
的自定义实现。我没有显示此课程的完整代码,因为它并不有趣。此类将用户标识符设置为当前线程。将用户标识符设置为TaskScheduler
变量。
UserId
我创建了自定义public sealed class CustomTaskScheduler : TaskScheduler
{
// Sets user information to the variable which is marked ThreadStatisAttribute.
}
,它将自定义调度程序作为构造函数的参数。
TaskFactory
最后我有public sealed class CustomTaskFactory : TaskFactory
{
public CustomTaskFactory(CustomTaskScheduler taskScheduler) : base(taskScheduler) { }
}
类执行异步操作。
Service
嗯,公平地说,我有两个问题:
public sealed class Service
{
private readonly CustomTaskScheduler customTaskScheduler;
private readonly CustomTaskFactory customTaskFactory;
private readonly SomeClient someClient;
public Service()
{
this.customTaskScheduler = new CustomTaskScheduler();
this.customTaskFactory = new CustomTaskFactory(this.customTaskScheduler);
this.someClient = new SomeClient();
}
public void DoSomething(string param)
{
this.customTaskFactory.StartNew(() => testAsync(param)).Unwrap().Wait();
// This method will use the result which is given by async operation which is called above.
DoSomethingElseSynchronously();
}
private async Task DoSomethingAsync()
{
Thread.Sleep(1000);
int result1 = await this.customTaskFactory.StartNew(() => PerformAsyncOperation(default(int))).Unwrap();
Thread.Sleep(1000);
int result2 = await this.customTaskFactory.StartNew(() => PerformAsyncOperation(default(int))).Unwrap();
int sum = result1 + result2;
}
private async Task<int> PerformAsyncOperation(int x)
{
Thread.Sleep(1000);
return await this.customTaskFactory.StartNew(() => CallClientAsync(x)).Unwrap();
}
private async Task<int> CallClientAsync(int x)
{
Thread.Sleep(1000);
int resultObtainedFromClient1 = await this.customTaskFactory.StartNew(async () => await this.someClient.GetAsync(x)).Unwrap();
Thread.Sleep(1000);
int resultObtainedFromClient2 = await this.customTaskFactory.StartNew(async () => await this.someClient.GetAsync(x)).Unwrap();
int result = resultObtainedFromClient1 + resultObtainedFromClient2;
return result;
}
}
和await this.customTaskFactory.StartNew(async () => await this.someClient.GetAsync(x)).Unwrap()
有什么区别我想回忆一下,我对await this.customTaskFactory.StartNew(() => this.someClient.GetAsync(x)).Unwrap()
变量ThreadStatic
感兴趣。据我所知,第一个调用将在调用UserId
方法的同一个线程中执行,在这种情况下我的线程静态字段将被填充。在第二个调用中,我将异步方法作为StartNew
方法的参数。这意味着该任务将包含异步方法,该方法可能由另一个线程执行,而另一个线程将不包含我的StartNew
变量。
UserId
变量。丢失UserId
数据时是否有任何情况?怎么预防呢?提前致谢