Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CSharp_黄谦_无25 #20

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions hw1/hw1/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,75 @@ public class LongProgressByTime: ILongProgressByTime

//挑战:利用原子操作
//long.MaxValue非常久

private readonly object _lock = new();
private bool isReady = true;
public long NeedTime { get; private set; }
public long StartTime { get; private set; }

/// <summary>
/// 尝试加载下一次进度条,needTime指再次加载进度条所需时间,单位毫秒
/// 如果之前进度条处于就绪态,则将进度开始下一次加载,返回true
/// 如果之前进度条不处于就绪态,返回false
/// </summary>
public bool Start(long needTime)
{
lock (_lock)
{
if (isReady)
{
isReady = false;
NeedTime = needTime;
StartTime = Environment.TickCount64;
return true;
}
else
{
return false;
}
}
}

/// <summary>
/// 使未完成的进度条清零并终止变为就绪态,返回值代表是否成功终止
/// </summary>
public bool TrySet0()
{
bool flag = Environment.TickCount64 - StartTime >= NeedTime && !isReady;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

即便是读取也应该上锁

lock (_lock)
{
if (flag)
{
return false;
}
else
{
StartTime = Environment.TickCount64;
isReady = true;
return true;
}
}
}

/// <summary>
/// 使进度条强制清零并终止变为就绪态
/// </summary>
public void Set0()
{
lock (_lock)
{
StartTime = Environment.TickCount64;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这样的话读取GetProgress()时进度是不正确的

isReady = true;
}
}

/// <summary>
/// ElapsedTime指其中已过去的时间,NeedTime指当前Progress完成所需时间,单位毫秒
/// </summary>
public (long ElapsedTime, long NeedTime) GetProgress()
{
return (Environment.TickCount64 - StartTime, NeedTime);
}
}

/*输出示例(仅供参考):
Expand Down